Section 6.3 Arrays: Array Initializers#
Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.3 Array Initializers
Brian (Beej Jorgensen) Hall Website
Program for Initializing an Array from a List#
#include <stdio.h>
int main(void)
{
int i;
int a[5] = {22, 37, 3490, 18, 95}; // Initialize with these values
for (i = 0; i < 5; i++) {
printf("%d\n", a[i]);
}
}
Explanation of the Above Code#
This C code demonstrates how to initialize an array with specific values and iterate through it to print each element.
Code Breakdown:#
#include <stdio.h>
The
#include <stdio.h>
directive includes the standard input/output library, which provides theprintf
function for printing to the console.
int main(void)
The
main
function is the entry point of the program.
int i;
int a[5] = {22, 37, 3490, 18, 95}; // Initialize with these values
int i;
: Declares a variablei
to be used as a loop counter.int a[5] = {22, 37, 3490, 18, 95};
: Declares an integer arraya
of size 5 and initializes it with the values{22, 37, 3490, 18, 95}
.
for (i = 0; i < 5; i++) {
printf("%d\n", a[i]);
}
A
for
loop is used to iterate through the arraya
.i = 0
: The loop starts withi
set to 0.i < 5
: The loop continues as long asi
is less than 5 (the size of the array).i++
: Incrementsi
by 1 after each iteration.
Inside the loop,
printf("%d\n", a[i]);
prints the value of thei
-th element of the arraya
followed by a newline (\n
).
Output:#
The program will print each element of the array on a new line:
22
37
3490
18
95
Key Concepts:#
Array Initialization: The array
a
is initialized with specific values at the time of declaration.Iteration: The
for
loop iterates through the array using the indexi
.Accessing Array Elements: The array elements are accessed using the syntax
a[i]
, wherei
is the index.
This program demonstrates a simple way to initialize and process arrays in C.
Compile and Run Code#
Use Python to Change to Working Directory#
import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "C_Code"
os.chdir(code_dir)
build_command = os.system("gcc -o section_6_3_array_initializers section_6_3_array_initializers.c")
exec_status = os.system("./section_6_3_array_initializers")
22
37
3490
18
95