2D Array in C

2D Array in C. 2D Array in C Tutorial. Learn 2D Array in C
2D Array in C.

What is 2D Array ?

A two-dimensional array is a collection of elements of the same data type arranged in a grid of rows and columns.

Syntax of 2D Array in C:

data_type array_name[row_size][column_size];

Here, data_type is the data type of the elements in the array, array_name is the name of the array, row_size is the number of rows in the array, and column_size is the number of columns in the array.

Two-dimensional arrays are used when we need to store data in a tabular format, such as a matrix or a table.

Declaration and Initialization of 2D Array

We can declare and initialize a two-dimensional array in C using the following syntax:

data_type array_name[row_size][column_size] = {{val11, val12, ... val1n}, {val21, val22, ... val2n}, ... {valm1, valm2, ... valmn}};

Here, valij represents the value of the element in the ith row and jth column of the array.

Examples of 2D Array

1. Multiplication Table from 1 to 10

#include <stdio.h>

int main() {
  int mult_table[10][10];

  // initialize the array with multiplication values
  for(int i=0; i<10; i++) {
    for(int j=0; j<10; j++) {
      mult_table[i][j] = (i+1) * (j+1);
    }
  }

  // print the array
  for(int i=0; i<10; i++) {
    for(int j=0; j<10; j++) {
      printf("%4d", mult_table[i][j]);
    }
    printf("\n");
  }

  return 0;
}

Output:

   1   2   3   4   5   6   7   8   9  10
   2   4   6   8  10  12  14  16  18  20
   3   6   9  12  15  18  21  24  27  30
   4   8  12  16  20  24  28  32  36  40
   5  10  15  20  25  30  35  40  45  50
   6  12  18  24  30  36  42  48  54  60
   7  14  21  28  35  42  49  56  63  70
   8  16  24  32  40  48  56  64  72  80
   9  18  27  36  45  54  63  72  81  90
  10  20  30  40  50  60  70  80  90 100

Explanation:

In above example, we have declared a two-dimensional array table of size 10 x 10 to store the multiplication table of 10×10. We have initialized the array with the product of row and column numbers using nested for loops. We then print the array using nested for loops and printf statement.

2. Displaying Points

#include <stdio.h>

int main() {
  int points[3][2] = {{2, 3}, {5, 7}, {8, 1}};

  // print the array
  for(int i=0; i<3; i++) {
    printf("Point %d: (%d, %d)\n", i+1, points[i][0], points[i][1]);
  }

  return 0;
}

Output:

Point 1: (2, 3)
Point 2: (5, 7)
Point 3: (8, 1)

Explanation:

In above example, we have declared a two-dimensional array points of size 3 x 2 to store the coordinates of 3 points in 2D space. We have initialized the array with some sample coordinates using the initialization syntax. We then print the array using a for loop and print statement.

3. Storing Scores of Students

#include <stdio.h>

#define NUM_STUDENTS 4
#define NUM_SUBJECTS 3

int main() {
  int scores[NUM_STUDENTS][NUM_SUBJECTS];

  // Input scores for each student
  for (int i = 0; i < NUM_STUDENTS; i++) {
    printf("Enter scores for Student %d:\n", i+1);
    for (int j = 0; j < NUM_SUBJECTS; j++) {
      printf("Subject %d: ", j+1);
      scanf("%d", &scores[i][j]);
    }
    printf("\n");
  }

  // Print the scores
  printf("Student Scores:\n");
  for (int i = 0; i < NUM_STUDENTS; i++) {
    printf("Student %d: ", i+1);
    for (int j = 0; j < NUM_SUBJECTS; j++) {
      printf("%d ", scores[i][j]);
    }
    printf("\n");
  }

  return 0;
}

Output:

Enter scores for Student 1:
Subject 1: 85
Subject 2: 90
Subject 3: 78

Enter scores for Student 2:
Subject 1: 92
Subject 2: 88
Subject 3: 95

Enter scores for Student 3:
Subject 1: 76
Subject 2: 83
Subject 3: 80

Enter scores for Student 4:
Subject 1: 89
Subject 2: 92
Subject 3: 86

Student Scores:
Student 1: 85 90 78
Student 2: 92 88 95
Student 3: 76 83 80
Student 4: 89 92 86

Explanation:

In above example, we declare a 2D array scores to store the scores of students in a class. The array dimensions are determined by the number of students and the number of subjects. We use nested loops to input scores for each student and then print the scores using nested loops as well.

4. Matrix Multiplication

#include <stdio.h>

#define ROWS_A 2
#define COLS_A 3
#define ROWS_B COLS_A
#define COLS_B 4

void multiplyMatrices(int A[][COLS_A], int B[][COLS_B], int C[][COLS_B]) {
  for (int i = 0; i < ROWS_A; i++) {
    for (int j = 0; j < COLS_B; j++) {
      C[i][j] = 0;
      for (int k = 0; k < COLS_A; k++) {
        C[i][j] += A[i][k] * B[k][j];
      }
    }
  }
}

void printMatrix(int matrix[][COLS_B], int rows, int cols) {
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      printf("%d ", matrix[i][j]);
    }
    printf("\n");
  }
}

int main() {
  int matrixA[ROWS_A][COLS_A] = {
    {1, 2, 3},
    {4, 5, 6}
  };

  int matrixB[ROWS_B][COLS_B] = {
    {7, 8, 9, 10},
    {11, 12, 13, 14},
    {15, 16, 17, 18}
  };

  int matrixC[ROWS_A][COLS_B];

  multiplyMatrices(matrixA, matrixB, matrixC);

  printf("Matrix A:\n");
  printMatrix(matrixA, ROWS_A, COLS_A);

  printf("Matrix B:\n");
  printMatrix(matrixB, ROWS_B, COLS_B);

  printf("Matrix C (A x B):\n");
  printMatrix(matrixC, ROWS_A, COLS_B);

  return 0;
}

Output:

Matrix A:
1 2 3
4 5 6
Matrix B:
7 8 9 10
11 12 13 14
15 16 17 18
Matrix C (A x B):
74 80 86 92
173 188 203 218

Explanation:

In above example, we define two matrices matrixA and matrixB and declare an empty matrix matrixC. We implement the multiplyMatrices function to perform matrix multiplication and store the result in matrixC. Finally, we use the printMatrix function to print the original matrices and the result. The matrix multiplication operation involves nested loops to iterate through the elements of the matrices and perform the necessary calculations.

Rules to follow when using 2D Array in C:

  1. Declaration and Initialization: The 2D array must be declared and initialized with the appropriate size and values before using it. The size should be specified for both dimensions.
  2. Indexing: The elements of a 2D array are accessed using two indices: one for the row and another for the column. The row index comes first, followed by the column index. For example, array[row][col] accesses the element at row row and column col.
  3. Bounds Checking: It is essential to ensure that the indices used to access the array elements are within the valid bounds of the array. Accessing elements outside the array’s bounds can lead to undefined behavior or runtime errors.
  4. Row and Column Count: When passing a 2D array to a function, the number of rows and columns should be explicitly specified, either as separate arguments or using preprocessor constants.
  5. Memory Layout: In memory, a 2D array is stored in row-major order. This means that the elements of a row are stored consecutively in memory, followed by the elements of the next row.
  6. Array Initialization: A 2D array can be initialized during declaration using nested curly braces. The number of values provided should match the size of the array.
  7. Multidimensional Arrays: C allows arrays of higher dimensions beyond 2D. The rules and concepts discussed for 2D arrays apply to multidimensional arrays as well.
  8. Passing to Functions: When passing a 2D array to a function, it is passed as a pointer to an array. The number of columns in the array parameter should match the number of columns in the original array.
  9. Dynamic Memory Allocation: If the size of the array needs to be determined at runtime, dynamic memory allocation techniques, such as malloc or calloc, can be used to allocate memory for the 2D array.
  10. Array Copying: To copy a 2D array to another array, element-wise copying is required. You need to iterate through each element and assign the values from one array to the other.

More: