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 the printf 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 variable i to be used as a loop counter.

  • int a[5] = {22, 37, 3490, 18, 95};: Declares an integer array a 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 array a.

    • i = 0: The loop starts with i set to 0.

    • i < 5: The loop continues as long as i is less than 5 (the size of the array).

    • i++: Increments i by 1 after each iteration.

  • Inside the loop, printf("%d\n", a[i]); prints the value of the i-th element of the array a 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:#

  1. Array Initialization: The array a is initialized with specific values at the time of declaration.

  2. Iteration: The for loop iterates through the array using the index i.

  3. Accessing Array Elements: The array elements are accessed using the syntax a[i], where i 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