Nearby lessons
41 of 72C - Two Dimensional Array
A two-dimensional array stores values in rows and columns, like a table. In this tutorial, you will learn how to declare, initialize, access, and display a 2D array using simple C programs.
What Is a Two-Dimensional Array?
A two-dimensional array (2D array) stores multiple values in rows and columns.
Think of a classroom table with 2 rows and 3 columns. Each position stores one value.
Example:
10 20 30 40 50 60
Here, the array contains 2 rows and 3 columns.
Syntax of a Two-Dimensional Array
The basic syntax is:
data_type array_name[rows][columns];
- data_type: Type of values, such as int or float.
- array_name: Name of the array.
- rows: Number of rows.
- columns: Number of columns.
For example, int numbers[2][3]; creates an array with 2 rows and 3 columns. It can store 6 integer values.
Initializing a Two-Dimensional Array
We can assign values to a 2D array when declaring it. Each pair of inner braces represents one row.
Accessing Array Elements
We use two indexes to access a 2D array element:
array_name[row_index][column_index]
Remember:
- The first row has index 0.
- The first column has index 0.
numbers[0][1]means the first row and second column.numbers[1][2]means the second row and third column.
Updating Array Elements
We can change an element by assigning a new value to its row and column indexes.
Displaying Elements Using Nested Loops
A nested loop means using one loop inside another loop.
- The outer loop handles the rows.
- The inner loop handles the columns.
This method helps us display all elements of a 2D array.
Taking Input from the User
We can use nested loops and scanf() to accept values from the user.
Here, the user enters 4 values for an array containing 2 rows and 2 columns.
Finding the Sum of All Elements
We can use nested loops to add all elements of a 2D array.
Adding Two Matrices
Matrix addition means adding the values at the same positions in two matrices.
For example:
First matrix: Second matrix: 1 2 5 6 3 4 7 8 Result: 6 8 10 12
Both matrices must have the same number of rows and columns.
Common Mistakes
- Wrong index: Remember that array indexes start from 0.
- Wrong loop condition: For 2 rows, use
i < 2. - Missing index: Use both row and column indexes, such as
numbers[0][1]. - Wrong array size: Do not access elements outside the declared rows and columns.
- Missing ampersand: Use
&numbers[i][j]withscanf().
- A 2D array stores values in rows and columns.
- Syntax: data_type array_name[rows][columns].
- Array indexing starts from 0.
- The outer loop handles rows.
- The inner loop handles columns.
- Nested loops are used to process 2D arrays.