Section 6.1 Arrays: An Easy Example#

Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.1 An Easy Example

Brian (Beej Jorgensen) Hall Website

Program for Creating, Initializing, and Printing an Array#

#include <stdio.h>

int main(void)
{
    int i;
    float f[4];  // Declare an array of 4 floats

    f[0] = 3.14159;  // Indexing starts at 0, of course.
    f[1] = 1.41421;
    f[2] = 1.61803;
    f[3] = 2.71828;

    // Print them all out:

    for (i = 0; i < 4; i++) {
        printf("%f\n", f[i]);
    }
}

Explanation of the Above Code#

  1. Include the Standard I/O Library: The program starts by including the standard input/output library with #include <stdio.h>, which allows us to use functions like printf().

  2. Main Function: The main() function is the entry point of the program.

  3. Variable Declaration: Inside the main() function, we declare an integer variable i and a float array f with 4 elements.

  4. Array Initialization: We assign values to each element of the array f using indexing. The first element is f[0], the second is f[1], and so on.

  5. Loop to Print Values: We use a for loop to iterate through the array and print each value using printf(). The loop runs from 0 to 3, which corresponds to the indices of the array.

  6. Output: The program prints the values of the array f to the console, each on a new line.

Output of the Program#

When you run the program, it will output the following values:

3.141590
1.414210
1.618030
2.718280

Summary#

This simple program demonstrates how to create, initialize, and print an array in C. It uses a for loop to iterate through the array and print each value, showcasing the basic syntax and functionality of arrays in C programming.

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_1_easy_example section_6_1_easy_example.c")
exec_status = os.system("./section_6_1_easy_example")
3.141590
1.414210
1.618030
2.718280