Multidimensional Arrays in C / C++

Configurare noua (How To)

Situatie

In C/C++, we can define multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row-major order).

Solutie

Pasi de urmat

Size of multidimensional arrays

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
Two-Dimensional Array

Two – dimensional array is the simplest form of a multidimensional array. We can see a two – dimensional array as an array of one – dimensional array for easier understanding.

The basic form of declaring a two-dimensional array of size x, y:
Syntax: 

data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.

We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:

int x[10][20];

Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and ‘j’ is the column number.

A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below:

Lightbox

Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional array can be initialized.
First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order, the first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.
Better Method:

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

This type of initialization makes use of nested braces. Each set of inner braces represents one row. In the above example, there is a total of three rows so there are three sets of inner braces.
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes.
Example:

int x[2][1];

The above example represents the element present in the third row and second column.

// C++ Program to print the elements of a
// Two-Dimensional array
#include<iostream>
using namespace std;
int main()
{
// an array with 3 rows and 2 columns.
int x[3][2] = {{0,1}, {2,3}, {4,5}};
// output each array element’s value
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
cout << “Element at x[” << i
<< “][” << j << “]: “;
cout << x[i][j]<<endl;
}
}
return 0;
}

Tip solutie

Permanent

Voteaza

(9 din 18 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?