Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

2D Arrays in C: Declaration, Initialization, and Usage

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

Data can be stored in ordered memory within an array. Its nature is particular, and it has a determined limit. We can reach the elements by using an index number. Usually, numbers begin with index 0. At index 0 lies the first element, and index 1 represents the second. Working with known numbers greatly benefits from using arrays. There are three types: single-dimensional arrays, two-dimensional arrays, and other types. This discusses two-dimensional arrays in C.

What are Arrays?

The array is a linear structure that distributes each element directly in a continuous memory unit on the computer system. Elements have similar types and can be reached via indices. Indices allow fast access to individual elements, each residing in a neighboring memory area.

Definitions of 2D Arrays

A Two-Dimensional array is a powerful tool in the C language. It consists of rows and columns and stores data of a single type. It is declared with two dimensions that explain the number of rows and columns, and element access is allowed using two indices. For example, a declaration like int array[3] [4].  This defines a two-dimensional array of type int with three rows and four columns.

Declaration of Two-Dimensional Array

Managing two-dimensional arrays in C programming is quite simple. Data can be arranged in a two-dimensional layout accessible by the row and column indices.

 

Syntax

 

type  arrayName[rowSize] [columnSize] ;

 

  • type: The type of the elements stored in the array (eg, int, float , char).
  • arrayName: The name of the array
  • rowSize: The number of rows in the array.
  • columnSize: The number of columns in the array.

 

The following program demonstrates the program.

 

Program

#include <stdio.h> int main() { int matrix[2][2] = { {5,8}, {20,30} }; printf("Matrix Elements"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("n"); } matrix[1][2] = 100; printf("Matrix Elements after Modification:"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("n"); } int sum = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { sum += matrix[i][j]; } } printf("Sum of the elements: %d", sum); return 0; }

Output

Matrix Elements 5 8 20 20 30 4199056 Matrix Elements after Modification:5 8 20 20 30 100 Sum of the elements: 183

Accessing Elements of 2D Array

A two-dimensional array is an aggregate of arrays in which two subscripts can identify every item. One index for the row and one for the column. For example, we declared an array as an int matrix[3][4], which means a grid of three rows and four columns.  This way, we can refer to an element at some position in the form matrix[1][2]

 

type arrayName[numRows][numCols]

 

The following program demonstrates the Accessing Elements Array.

 

Program

#include<stdio.h> int main(){ int matrix[3][4] = { {5,8,9}, {8,9,10}, {30,40,11,23} } ; printf("Orginal Matrix") ; for(int i =0;i<3;i++){ for(int j =0;j<4;j++){ printf("%d",matrix[i][j]); } } printf("n") ; matrix[2][1] = 59 ; printf("nMatrix after modificationn") ; for(int i =0;i<3;i++){ for(int j = 0; j<4 ;j++){ printf("%d",matrix[i][j]) ; } printf("n"); } int *p = (int*) matrix ; printf("n We can acces the element using the Indexing in Cn") ; for(int i =0;i<12;i++){ printf("%d", *(p+i)) ; } printf("n") ; return 0 ; }

Output

Original Matrix58908910030401123 Matrix after modification 5890 89100 30591123 We can access the element using the Indexing in C 58908910030591123

Examples of 2 Dimensional Array

Two-dimensional arrays can be used in C for various purposes. Here, we describe a couple of C language programs that represent 2D arrays.

 

Example 1: Iterating Over a 2D Array

#include<stdio.h> int main(){ int matrix [2][3] ={ {1,2,3}, {4,5,6} } ; printf("Elements of the 2x3 matrix :n") ; for(int i=0;i<2;i++){ for(int j =0;j<3;j++){ printf("%d", matrix[i][j]) ; } printf("n") ; } matrix[1][2] = 200 ; printf("n Matrix after addition n") ; for(int i =0 ;i<2;i++){ for(int j =0;j<3;j++) { printf("%d",matrix[i][j]) ; } } printf("n") ; int sum =0 ;   for(int i  =0;i<2;i++){ for(int j =0; j<3 ;j++){ sum += matrix[i][j] ; } } printf("nSum of the elements %dn",sum) ; return 0  ; }  

Output 

Elements of the 2x3 matrix : 123 456 Matrix after addition 12345200 Sum of the elements 215

Example 2: Filling a 2D Array with User Input and Displaying It 

#include<stdio.h> int main(){ int matrix[2][2],i,j ; for(i=0;i<2;i++){ for(j=0;j<2;j++){ printf("Enter value for matrix [%d][%d]",i,j) ; scanf("%d", &matrix[i][j]) ; } } printf("nDisplaying the matrix: n") ; for(i=0 ;i<2 ;i++){ for(j =0 ;j<2;j++){ printf("%dt",matrix[i][j]) ; } printf("n") ; } return 0 ; }

Output

Enter value for matrix [0][0] = 30 Enter value for matrix [0][1] = 40 Enter value for matrix [1][0] = 50 Enter value for matrix [1][1] = 67   Displaying the matrix: 30        40 50        67

How to Allocate Memory in an Array?

For a 2D array representation method known as ‘column-major order’, contiguous memory allocation is applied.”.  This technique will make sure that each array element lies next to each other in memory. It promotes access speed and integrity.

 

The following program demonstrates the Allocated Memory.

 

Program

#include<stdio.h> int main(){ int i =0,j  =0 ; int arr[2][2] = { {5,8}, {20,30} } ; for(i = 0;i<2;i++){ for(j =0;j<2 ;j++){ printf("%d %d",arr[i][j]) ; } } return 0 ; }

Output

5 08 020 230 2
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Operations on Two-dimensional Arrays

In C language, Operations on two-dimensional arrays involve fundamental tasks and manipulations crucial for handling grid-like data structures. We can perform various operations on matrices for mathematics, physics, engineering, and computer science, including multiplication and transposing.

Multiplication of 2D Arrays

We’ll multiply the 2D Array matrix, which might be done through an algorithm combining rows and columns to create a new matrix. All elements in the resulting matrix are some kind of sum of products of elements from the row of the first matrix and columns of the second matrix. Let’s now see the following program. The program involves the 2D array and performs multiplication.

 

The following program demonstrates the multiplication of 2D arrays.

 

Program

#include <stdio.h> #define MAX 10 int main() { int first[2][3] = { {1, 2, 3}, {4, 5, 6} }; int second[3][2] = { {7, 8}, {9, 10}, {11, 12} }; int result[2][2]; int r1 = 2, c1 = 3, r2 = 3, c2 = 2; for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { result[i][j] = 0; } } for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { result[i][j] += first[i][k] * second[k][j]; } } } printf("Resultant Matrix:n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { printf("%d ", result[i][j]); } printf("n"); } return 0; }

Output:

Resultant Matrix: 58 64 139 154

Transpose of a 2D Array

In this section the concept of transposition of a 2D array or matrix with dimensions m*n is described. The transpose of given array will have dimensions of n*m.  In each of the input integer values of [i][j], all of them shall be moved to the [j][i] in the transposed 2D array.

 

Program

#include <stdio.h> int main() { int rows = 3, cols = 3; int matrix[3][3] = { {1343, 253, 3334}, {4343, 5343, 6334}, {734, 343, 9343} }; int transpose[3][3]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transpose[j][i] = matrix[i][j]; } } printf("Original Matrix:n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("n"); } printf("nTransposed Matrix:n"); for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { printf("%d ", transpose[i][j]); } printf("n"); } return 0; }

Output

Original Matrix: 1343 253 3334 4343 5343 6334 734 343 9343   Transposed Matrix: 1343 4343 734 253 5343 343 3334 6334 9343

Passing 2D Arrays to Functions

The C language also supports passing 2D arrays to functions. The function needs a specialized syntax to know that the data is being passed in a 2D array. The function signature that takes 2D arrays as the argument is shown below.

 

returnType funName(arrType arr_name[m][n], int m , int n)

 

Number m refers to rows and number n to the columns. To communicate row and column sizes is essential for an array whose addresses get transmitted as pointers.

 

The following program demonstrates that Array functions in C.

 

Program

#include <stdio.h> #define Row 3 #define Col 4 void printArray(int arr[][Col], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < Col; j++) { printf("%d ", arr[i][j]); } printf("n"); } } int main() { int array[Row][Col] = { {90, 23, 35, 43}, {55, 63, 73, 834}, {98, 10, 11, 12} }; printArray(array, Row) ; return 0; }

Output

90 23 35 43 55 63 73 834 98 10 11 12

Dynamic Memory Allocation in 2D Array

Dynamic Memory Allocation for 2D arrays in C: This calls for using pointers and functions like malloc or calloc to make space in memory at runtime. This feature enables programmers to build flexible data structures whose size can be ascertained at runtime rather than compile time. Flexibility is an absolute necessity for applications wherein we are unaware of array dimensions before coding or changing.

 

Program

#include <stdio.h> #include <stdlib.h> int main() { int rows = 3, cols = 3; int **array; array = (int **)malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { array[i] = (int *)malloc(cols * sizeof(int)); }   int value = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { array[i][j] = value++; } } printf("2D Array:n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", array[i][j]); } printf("n"); } for (int i = 0; i < rows; i++) { free(array[i]); } free(array);   return 0; }

Output

2D Array: 1 2 3 4 5 6 7 8 9

Conclusion

This article explored 2D arrays in C necessary for working with tabular data including matrices or grids. Int matrix[3][3] creates a 2D array. This establishes a 3×4 dimensional array. To correctly index a 2D array passed to a function both the array and its dimensions need to be supplied.

FAQs
Data has been laid out in a row-major format where consecutive row elements reside in memory.
Available memory controls the size which may change with the compiler and hardware configuration..
When initiating just a subset of the array's elements their values default to zero.
A 2D array cannot resize a statically allocated 2D array after its declaration. For dynamic arrays, you need to allocate a new array and copy elements if you need a larger or smaller array.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved