Create Two-Dimensional Arrays in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to create and manipulate two-dimensional arrays in C. You will start by declaring two-dimensional arrays, then explore various methods to initialize them. Next, you will learn how to access and manipulate the elements of the arrays. Finally, you will apply your knowledge to compute the average marks for two subjects and enhance the functionality of the two-dimensional arrays. This lab provides a comprehensive understanding of working with two-dimensional arrays in the C programming language.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/CompoundTypesGroup -.-> c/structures("`Structures`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") c/BasicsGroup -.-> c/data_types("`Data Types`") subgraph Lab Skills c/output -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/for_loop -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/arrays -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/memory_address -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/pointers -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/structures -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/math_functions -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} c/data_types -.-> lab-438259{{"`Create Two-Dimensional Arrays in C`"}} end

Declare Two-Dimensional Arrays

In this step, you'll learn how to declare two-dimensional arrays in C, which are essentially arrays of arrays that allow you to store data in a grid-like structure with rows and columns.

Let's start by creating a new C file to demonstrate two-dimensional array declaration:

touch ~/project/two_dimensional_arrays.c

Now, let's write our first two-dimensional array declaration:

#include <stdio.h>

int main() {
    // Declare a 3x4 integer two-dimensional array
    int grades[3][4];

    return 0;
}

In this example, grades is a two-dimensional array with 3 rows and 4 columns. This means it can store a total of 12 integer values (3 ร— 4 = 12).

Let's explore different ways of declaring two-dimensional arrays, appending the following code to the file:

// Method 1: Declaration with initialization
int matrix[2][3] = {
    {1, 2, 3},   // First row
    {4, 5, 6}    // Second row
};

// Method 2: Partial initialization
int scores[3][3] = {
    {10, 20, 30},
    {40, 50}     // Remaining elements will be zero
};

// Method 3: Flattened initialization
int simple_matrix[2][3] = {1, 2, 3, 4, 5, 6};

Compile and run the program to verify:

gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays

Example output will be an empty program execution since we haven't added any print statements.

Key points about two-dimensional array declaration:

  • The first bracket represents rows
  • The second bracket represents columns
  • You can initialize partially or fully
  • Uninitialized elements are automatically set to zero
  • Total elements = rows ร— columns

Initialize Two-Dimensional Arrays

In this step, you'll learn various methods to initialize two-dimensional arrays in C, building upon the declaration skills from the previous step.

Let's modify the previous file to explore different initialization techniques.

Now, replace the existing code with the following initialization methods:

#include <stdio.h>

int main() {
    // Method 1: Complete initialization
    int scores[3][4] = {
        {85, 92, 78, 90},    // First row
        {76, 88, 95, 82},    // Second row
        {63, 71, 89, 93}     // Third row
    };

    // Method 2: Partial initialization
    int temperatures[2][3] = {
        {25, 30, 22},        // First row
        {28}                 // Partial second row
    };

    // Method 3: Flattened initialization
    int matrix[2][3] = {1, 2, 3, 4, 5, 6};

    // Method 4: Initialize all elements to zero
    int zeros[3][3] = {0};

    // Print the first method to demonstrate
    printf("Student Scores:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", scores[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run the program:

gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays

Example output:

Student Scores:
85 92 78 90
76 88 95 82
63 71 89 93

Key initialization methods:

  1. Complete initialization: Specify values for each row
  2. Partial initialization: Unspecified elements are set to zero
  3. Flattened initialization: Values filled row by row
  4. Zero initialization: All elements set to zero

Important points:

  • You can partially initialize arrays
  • Unspecified elements are automatically set to zero
  • The total number of initializers cannot exceed array size
  • Nested braces help clarify row-wise initialization

Access Two-Dimensional Array Elements

In this step, you'll learn how to access individual elements in a two-dimensional array using indexing and nested loops in C.

Let's update our previous file to demonstrate element access.

Add the following code to explore different ways of accessing array elements:

#include <stdio.h>

int main() {
    // Create a 3x4 student grades array
    int grades[3][4] = {
        {85, 92, 78, 90},    // First student's grades
        {76, 88, 95, 82},    // Second student's grades
        {63, 71, 89, 93}     // Third student's grades
    };

    // Method 1: Direct element access
    printf("First student's first grade: %d\n", grades[0][0]);
    printf("Second student's third grade: %d\n", grades[1][2]);

    // Method 2: Accessing elements using nested loops
    printf("\nAll grades using nested loops:\n");
    for (int student = 0; student < 3; student++) {
        for (int subject = 0; subject < 4; subject++) {
            printf("Student %d, Subject %d: %d\n",
                   student + 1, subject + 1, grades[student][subject]);
        }
    }

    // Method 3: Modifying array elements
    grades[2][3] = 95;  // Update last grade of third student
    printf("\nUpdated third student's last grade: %d\n", grades[2][3]);

    return 0;
}

Compile and run the program:

gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays

Example output:

First student's first grade: 85
Second student's third grade: 95

All grades using nested loops:
Student 1, Subject 1: 85
Student 1, Subject 2: 92
Student 1, Subject 3: 78
Student 1, Subject 4: 90
Student 2, Subject 1: 76
Student 2, Subject 2: 88
Student 2, Subject 3: 95
Student 2, Subject 4: 82
Student 3, Subject 1: 63
Student 3, Subject 2: 71
Student 3, Subject 3: 89
Student 3, Subject 4: 95

Updated third student's last grade: 95

Key points about accessing two-dimensional array elements:

  • Use two indices: array[row][column]
  • First index represents the row (vertical)
  • Second index represents the column (horizontal)
  • Indexing starts at 0
  • Nested loops are useful for traversing entire arrays
  • You can directly read and modify individual elements

Compute Average Marks for Two Subjects

In this step, you'll learn how to use two-dimensional arrays to calculate average marks for multiple students across different subjects.

Let's update our previous file to compute subject averages.

Add the following code to calculate and display average marks:

#include <stdio.h>

#define STUDENTS 5
#define SUBJECTS 3

int main() {
    // Create a two-dimensional array for student marks
    int marks[STUDENTS][SUBJECTS] = {
        {85, 92, 78},
        {76, 88, 95},
        {63, 71, 89},
        {90, 84, 77},
        {82, 79, 91}
    };

    // Arrays to store subject averages
    float subject_averages[SUBJECTS];

    // Compute average for each subject
    for (int subject = 0; subject < SUBJECTS; subject++) {
        int subject_total = 0;

        // Sum marks for current subject
        for (int student = 0; student < STUDENTS; student++) {
            subject_total += marks[student][subject];
        }

        // Calculate average
        subject_averages[subject] = (float)subject_total / STUDENTS;
    }

    // Display subject averages
    printf("Subject Averages:\n");
    for (int subject = 0; subject < SUBJECTS; subject++) {
        printf("Subject %d: %.2f\n", subject + 1, subject_averages[subject]);
    }

    // Bonus: Find highest and lowest subject average
    float highest_avg = subject_averages[0];
    float lowest_avg = subject_averages[0];
    int highest_subject = 0;
    int lowest_subject = 0;

    for (int subject = 1; subject < SUBJECTS; subject++) {
        if (subject_averages[subject] > highest_avg) {
            highest_avg = subject_averages[subject];
            highest_subject = subject;
        }
        if (subject_averages[subject] < lowest_avg) {
            lowest_avg = subject_averages[subject];
            lowest_subject = subject;
        }
    }

    printf("\nHighest Average: Subject %d (%.2f)\n",
           highest_subject + 1, highest_avg);
    printf("Lowest Average: Subject %d (%.2f)\n",
           lowest_subject + 1, lowest_avg);

    return 0;
}

Compile and run the program:

gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays

Example output:

Subject Averages:
Subject 1: 79.20
Subject 2: 82.80
Subject 3: 86.00

Highest Average: Subject 3 (86.00)
Lowest Average: Subject 1 (79.20)

Key concepts demonstrated:

  • Use of nested loops to process two-dimensional arrays
  • Calculating averages across rows and columns
  • Finding highest and lowest averages
  • Type casting to compute float averages
  • Defining constants for array dimensions

Enhance Two-Dimensional Array Functionality

In this final step, you'll learn advanced techniques to enhance two-dimensional array functionality, including passing arrays to functions, dynamic memory allocation, and creating more complex array operations.

Let's update our previous file to demonstrate these advanced concepts.

Replace the previous code with this comprehensive example:

#include <stdio.h>
#include <stdlib.h>

#define ROWS 3
#define COLS 4

// Function to print a two-dimensional array
void printArray(int arr[ROWS][COLS]) {
    printf("Array Contents:\n");
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%4d ", arr[i][j]);
        }
        printf("\n");
    }
}

// Function to transpose a two-dimensional array
void transposeArray(int original[ROWS][COLS], int transposed[COLS][ROWS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            transposed[j][i] = original[i][j];
        }
    }
}

int main() {
    // Static two-dimensional array
    int matrix[ROWS][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    // Print original array
    printf("Original Array:\n");
    printArray(matrix);

    // Transpose the array
    int transposed[COLS][ROWS];
    transposeArray(matrix, transposed);

    // Print transposed array
    printf("\nTransposed Array:\n");
    for (int i = 0; i < COLS; i++) {
        for (int j = 0; j < ROWS; j++) {
            printf("%4d ", transposed[i][j]);
        }
        printf("\n");
    }

    // Dynamic memory allocation for 2D array
    int **dynamicMatrix;
    dynamicMatrix = (int **)malloc(ROWS * sizeof(int *));
    for (int i = 0; i < ROWS; i++) {
        dynamicMatrix[i] = (int *)malloc(COLS * sizeof(int));
    }

    // Initialize dynamic matrix
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            dynamicMatrix[i][j] = i * COLS + j + 1;
        }
    }

    // Print dynamic matrix
    printf("\nDynamic Matrix:\n");
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%4d ", dynamicMatrix[i][j]);
        }
        printf("\n");
    }

    // Free dynamically allocated memory
    for (int i = 0; i < ROWS; i++) {
        free(dynamicMatrix[i]);
    }
    free(dynamicMatrix);

    return 0;
}

Compile and run the program:

gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays

Example output:

Original Array:
   1   2   3   4
   5   6   7   8
   9  10  11  12

Transposed Array:
   1   5   9
   2   6  10
   3   7  11
   4   8  12

Dynamic Matrix:
   1   2   3   4
   5   6   7   8
   9  10  11  12

Key advanced concepts demonstrated:

  • Passing two-dimensional arrays to functions
  • Array transposition
  • Dynamic memory allocation for 2D arrays
  • Memory management with malloc() and free()
  • Flexible array manipulation techniques

Summary

In this lab, you learned how to declare two-dimensional arrays in C, which are arrays of arrays that allow you to store data in a grid-like structure with rows and columns. You explored different methods of declaring and initializing two-dimensional arrays, including full initialization, partial initialization, and flattened initialization. You also learned that uninitialized elements are automatically set to zero, and the total number of elements in a two-dimensional array is determined by the product of the number of rows and columns.

Building on the declaration skills, you then learned various methods to initialize two-dimensional arrays in C, including assigning values row by row, column by column, or using a flattened approach. You also explored how to access individual elements within the two-dimensional array using row and column indices.

Other C Tutorials you may like