Two Dimensional Array in C Programming

Get Certified in C Programming and Take Your Skills to the Next Level

Arrays in C

Arrays are one of the most useful data structures in C programming. They allow storing and accessing multiple values of the same data type through a single identifier.

For example, an integer array can store multiple integer values that can be referenced by their index. This provides an efficient way to handle collections of data compared to using individual variables for each value.

Effective data management in C programs depends on understanding and using arrays. We will concentrate on two-dimensional arrays in this article, which are arrays that also contain other arrays as elements.

Understanding Two-Dimensional Arrays in C

An array of arrays makes up a two-dimensional (2D) array. It stores data in a grid-like structure with rows and columns. For example, a 2D array of integers with 3 rows and 5 columns can store 15 integer values.

Matrix structures, which can be thought of as a collection of rows and columns, are used to organize the 2D array. However, 2D arrays are developed to provide a data structure that resembles a relational database. It makes it simple to keep a large amount of data at once and transfer it to as many functions as needed.

Each element in the 2D array is identified by two indices – the row index and the column index. This provides a systematic way to locate and access individual elements, which is not possible with normal one-dimensional arrays.

Understanding Two Dimensional Arrays

Properties of Two-Dimensional Arrays in C

Two-dimensional arrays have several key properties:

  • Data type uniformity – All elements must have the same data type, e.g. int, float, etc.
  • Contiguous memory allocation – The elements are stored contiguously (next to each other) in memory.
  • Row-column association – The first index selects a row, and the second index selects a column in that row.
  • Random access – Elements can be accessed directly using their row and column indices.

Advantages and Disadvantages of C 2D Arrays

Advantages:

  • Efficient and structured data storage and manipulation.
  • Simplified representation of matrices and tables.
  • Easy access to elements through row/column indices.
  • Data is stored contiguously in memory, providing a good locality of reference.

Disadvantages:

  • Fixed-size is not suitable for expanding data sets.
  • Can be slow and inefficient for dynamic data handling compared to other structures like linked lists.
  • The entire array needs to be traversed for common operations like search.

Size of Two Dimensional Arrays in C

Let us See How We can Calculate the Size of Two Dimensional Array:

Suppose we have a two-dimensional integer array A[M][N]. To calculate the total number of elements, we simply multiply the size of the dimensions.

For example, if we have an array A[10][20], this means there are 10 rows and 20 columns. So the total size is 10 * 20 = 200 elements.

In general, for a 2D array with M rows and N columns, the total number of elements is calculated as:

Total elements = M * N

Where M is the number of rows and N is the number of columns in the 2D array. This gives us the total storage space taken up by the array. Knowing the total elements allows us to iterate through the array correctly.

Declaring and Initializing 2D Arrays in C

To declare a 2D array in C, the syntax is:

dataType arrayName[rows][columns];

For example, to declare a 2D array with 3 rows and 5 columns to store integers:

int arr[3][5];

This allocates memory for a 3×5 matrix with all elements initialized to 0 by default.

If the declaration and initialization are carried out concurrently, there is no need to provide the array size in the case of a 1D array. With 2D arrays, this won’t be possible, though. We will need to define the array’s second dimension, at the very least. The following declaration and definition can be made for the two-dimensional array.

int arr[3][2] = { {1, 2}, {3, 4}, {5, 6} };

This allocates a 3×2 array and initializes values row-wise.

Accessing Elements

Elements are accessed using row and column indices, with the first index selecting the row and the second selecting the column.

For a 2D array arr[3][5]:

  • arr[0][0] refers to row 0, column 0.
  • arr[1][3] refers to row 1, column 3.
  • arr[2][4] refers to row 2, column 4.

Let’s access and modify some values:

int arr[3][2] = { {1, 2}, {3, 4}, {5, 6} };

printf("%d ", arr[2][0]); // Prints 5 

arr[0][1] = 10; // Sets arr[0][1] to 10

Accessing out-of-bounds indices leads to undefined behavior in C.

Time Complexity: O(N*M)
Space Complexity:O(1)

Why Use 2D Arrays in C?

Two-dimensional arrays are extremely useful in C for many reasons:

  • Used in mathematical matrix operations.
  • Representation of grids like chessboards.
  • Storing tabular data from spreadsheets or CSV files.
  • Grid-based games like tic-tac-toe.
  • Pixel-based image processing and graphic design applications.

How are 2D Arrays in C Stored in the Memory?

Two-dimensional arrays must be stored linearly in memory due to sequential addressing. There are two main techniques:

Row- major mapping stores array elements row-wise. The first row is stored first, then the second row, and so on. Within each row, columns are stored contiguously.

Column- major mapping stores array elements column-wise. The first column is stored first, then the second column, and so on. Within each column, rows are stored contiguously.

Both techniques linearize the 2D array by laying out elements either row-wise or column-wise in memory. This allows 2D arrays to be allocated and accessed efficiently using linear memory addresses. The choice depends on language conventions and optimal access patterns.

Input and Output

To store data entered by a user into a 2D array in C, we need to use nested loops to iterate through each element.

The outer loop runs from 0 to X-1 to handle each row.
The inner for loop goes from 0 to Y-1 to iterate through each column in that particular row.
This allows us to print a prompt to enter a value for the specific index A[i][j] and then store the input at that index.

To store a 2D array:

for(i=0; i<rows; i++) {
  for(j=0; j<cols; j++) {
    scanf("%d", &arr[i][j]);
  } 
}

To print a 2D array:

for(i=0; i<rows; i++) {
   for(j=0; j<cols; j++) {
      printf("%d ", arr[i][j]);
   }
   printf("\n");
}

This traverses each element using nested loops and row/column indices.

Examples C programs

1. Matrix Addition

#include <stdio.h>

int main() {
  int matrixX[3][3] = { {11, 22, 33}, {44, 55, 66}, {77, 88, 99} };
  int matrixY[3][3] = { {99, 88, 77}, {66, 55, 44}, {33, 22, 11} };
  int matrixResult[3][3]; // To store the sum of matrices

  // Adding corresponding elements
  for(int k = 0; k < 3; k++) {
    for(int l = 0; l < 3; l++) {
      matrixResult[k][l] = matrixX[k][l] + matrixY[k][l];
    }
  }

  // Displaying the result 
  printf("Sum of matrices:\n");
  for(int k = 0; k < 3; k++) {
    for(int l = 0; l < 3; l++) {
      printf("%d ", matrixResult[k][l]);
    }
    printf("\n");
  }

  return 0;
}

Output:
Sum of matrices:
110 110 110
110 110 110
110 110 110

This program demonstrates matrix addition using a 2D array. Three 2D arrays – matrixX, matrixY, and matrixResult – are declared. matrixX and matrixY are initialized with values representing two 3×3 matrices.

The program uses nested for loops to iterate through each element of matrixX and matrixY and stores the sum in the corresponding index of matrixResult. This relies on the row-column association property of 2D arrays for easy access.

Finally, it prints the elements of matrixResult to display the sum matrix. This code efficiently performs matrix addition using 2D arrays.

2. Transpose of a Matrix

This program finds the transpose of a matrix by interchanging rows and columns.

#include <stdio.h>

int main() {
  
  int A[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
  
  int transpose[3][3]; 
  
  // Swapping rows and columns
  for(int i=0; i<3; i++) {
    for(int j=0; j<3; j++) {
      transpose[j][i] = A[i][j];
    }
  }

  // Displaying transpose
  printf("Transpose of the matrix: \n");
  for(int i=0; i<3; i++) {
    for(int j=0; j<3; j++) {
      printf("%d ", transpose[i][j]);
    }
    printf("\n"); 
  }

  return 0;
}

Output:
Transpose of the matrix:
1 4 7
2 5 8
3 6 9

This program finds the transpose of a matrix using a 2D array. The transpose is obtained by interchanging the rows and columns of the original matrix.

We declare a 2D array A and initialize it with a sample 3×3 matrix. We also declare an empty array transpose to store the transpose.

Inside nested loops, we swap the row and column indices when assigning elements from A to transpose. This results in the interchanging of rows and columns.

Finally, we print the transpose array to display the new matrix. This demonstrates use of 2D arrays to manipulate matrices and access elements easily.

Common Operations in C

1) Traversal –

Accessing each element using nested loops:

#include <stdio.h>

int main() {
  int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

  for(int i=0; i<3; i++) {
    for(int j=0; j<4; j++) {
      printf("%d ", arr[i][j]);
    }
    printf("\n");
  }
}

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

2) Search –

Finding an element using sequential search:

#include <stdio.h>

int search(int arr[][4], int key, int r, int c){
  for(int i=0; i<r; i++){
    for(int j=0; j<c; j++){
      if(arr[i][j] == key)
        return 1;
    }
  }
  return 0;
}

int main() {
  int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
  
  int ans = search(arr, 8, 3, 4);
  if (ans) {
    printf("Key found!"); 
  } else {
    printf("Key not found!");
  }
}

Output:
Key found!

3) Sorting –

Sorting array elements using insertion sort:

#include <stdio.h>

void insertionSort(int arr[][4], int m, int n) {
  int i, j, key;
  for (i = 1; i < m; i++) {
    for (j = 1; j < n; j++) {
      key = arr[i][j];
      int k = j - 1;
      while (k >= 0 && arr[i][k] > key) {
        arr[i][k+1] = arr[i][k];
        k--;
      }
      arr[i][k+1] = key;
    }
  }
}

int main() {
  
  int arr[3][4] = { {5, 2, 8, 7}, {3, 1, 6, 9}, {4, 0, 2, 1}};
  
  insertionSort(arr, 3, 4);
  
  for (int i=0; i<3; i++) {
    for (int j=0; j<4; j++) {
      printf("%d ", arr[i][j]); 
    }
    printf("\n");
  }

  return 0;
}

Output:
0 1 2 3
1 2 6 7
2 4 5 8

4) Manipulation –

Swapping two elements:

#include <stdio.h>

void swap(int arr[][4], int r1, int c1, int r2, int c2){

  int temp = arr[r1][c1];
  arr[r1][c1] = arr[r2][c2];
  arr[r2][c2] = temp;

}

int main() {

  int arr[3][4]; // Initialized somehow

  swap(arr, 0, 1, 2, 3); // Swaps arr[0][1] and arr[2][3]
  
}

Pointers and 2D Arrays in C

In C, a 2D array is essentially an array of arrays. Each element in the 2D array is actually a 1D array itself.

When we declare a pointer to a 2D array, such as:

int (*p)[cols];

This pointer ‘p’ points to an array of ints of size ‘cols’. So we can imagine the 2D array as multiple 1D arrays, and the pointer points to the first 1D array.

To access elements, we need to dereference the pointer twice – first to get the 1D array, then again to get the element within that array.

For example, with a 2D array A:

p = A; 
p[i] -> gives 1D array at row i
p[i][j] -> gives element at A[i][j]

So ‘p[i]’ dereferences to the ith 1D array, and p[i][j] gets the jth element in that array.

Example:

#include <stdio.h>

int main() {

  int A[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
  
  int (*p)[4];
  p = A;
  
  p[2][3] = 20;
  
  printf("A[2][3] = %d", A[2][3]); // Prints 20
  
}

Output:

A[2][3] = 20

Passing Arrays to Functions

When passed to a function, 2D arrays decay into pointers. So, the changes made by the function are reflected in the original array.

// Function to modify array
void modifyArray(int arr[][10], int r, int c) {

  arr[0][0] = 5; // Change value
  
}

int main() {

  int arr[10][10];
  
  modifyArray(arr, 10, 10);
  
  // arr[0][0] is now 5
  
}

Conclusion

Two-dimensional arrays are an essential concept in C to manage and organize data efficiently. They bring structure and order to data handling. With features like easy element access, contiguous data storage and support for algorithms like search and sort, 2D arrays should be part of every C programmer’s toolkit.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses
Image

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *