Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.3 Array Initializers
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 theprintffunction for printing to the console.
int main(void)The
mainfunction is the entry point of the program.
int i;
int a[5] = {22, 37, 3490, 18, 95}; // Initialize with these valuesint i;: Declares a variableito be used as a loop counter.int a[5] = {22, 37, 3490, 18, 95};: Declares an integer arrayaof 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
forloop is used to iterate through the arraya.i = 0: The loop starts withiset to 0.i < 5: The loop continues as long asiis less than 5 (the size of the array).i++: Incrementsiby 1 after each iteration.
Inside the loop,
printf("%d\n", a[i]);prints the value of thei-th element of the arrayafollowed by a newline (\n).
Output:¶
The program will print each element of the array on a new line:
22
37
3490
18
95Key Concepts:¶
Array Initialization: The array
ais initialized with specific values at the time of declaration.Iteration: The
forloop iterates through the array using the indexi.Accessing Array Elements: The array elements are accessed using the syntax
a[i], whereiis 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