Section 6.5 Arrays: Multidimensional Arrays#

Adapted from: “Beej’s Guide to C Programming” by Brian (Beej Jorgensen) Hall: Beej’s Guide to C Programming: 6.5 Multidimensional Arrays

Brian (Beej Jorgensen) Hall Website

Program for Demonstrating Multidimensional Arrays#

#include <stdio.h>

int main(void)
{
    int row, col;

    int a[2][5] = {      // Initialize a 2D array
        {0, 1, 2, 3, 4},
        {5, 6, 7, 8, 9}
    };

    for (row = 0; row < 2; row++) {
        for (col = 0; col < 5; col++) {
            printf("(%d,%d) = %d\n", row, col, a[row][col]);
        }
    }
}

Explanation of the Above Code#

This C program demonstrates the use of a multidimensional array (a 2D array) and how to iterate over it to access and print its elements.

Code Breakdown:#

  1. Header File:

    #include <stdio.h>
    
    • Includes the standard input/output library to use functions like printf.

  2. Main Function:

    int main(void)
    
    • The entry point of the program.

  3. Variable Declaration:

    int row, col;
    
    • Declares two integer variables, row and col, which will be used as loop counters to iterate through the rows and columns of the array.

  4. 2D Array Initialization:

    int a[2][5] = {
        {0, 1, 2, 3, 4},
        {5, 6, 7, 8, 9}
    };
    
    • Declares and initializes a 2D array a with 2 rows and 5 columns.

    • The first row contains {0, 1, 2, 3, 4}.

    • The second row contains {5, 6, 7, 8, 9}.

  5. Nested Loops:

    for (row = 0; row < 2; row++) {
        for (col = 0; col < 5; col++) {
            printf("(%d,%d) = %d\n", row, col, a[row][col]);
        }
    }
    
    • Outer Loop: Iterates over the rows of the array (row = 0 to 1).

    • Inner Loop: Iterates over the columns of the array (col = 0 to 4).

    • printf Statement: Prints the row index, column index, and the value at that position in the array (a[row][col]).

  6. Output:

    • The program prints each element of the 2D array along with its row and column indices in the format (row, col) = value.

Example Output:#

(0,0) = 0
(0,1) = 1
(0,2) = 2
(0,3) = 3
(0,4) = 4
(1,0) = 5
(1,1) = 6
(1,2) = 7
(1,3) = 8
(1,4) = 9

Key Concepts:#

  • 2D Arrays: Represented as a grid of rows and columns.

  • Nested Loops: Used to traverse each element of the 2D array.

  • printf: Displays the indices and values of the array elements.

Similar code found with 1 license type

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_5_multidimensional_arrays section_6_5_multidimensional_arrays.c")
exec_status = os.system("./section_6_5_multidimensional_arrays")
(0,0) = 0
(0,1) = 1
(0,2) = 2
(0,3) = 3
(0,4) = 4
(1,0) = 5
(1,1) = 6
(1,2) = 7
(1,3) = 8
(1,4) = 9