C++ Multidimensional Arrays
In this C++ tutorial, you will learn about Multidimensional arrays, what is Multidimensional array, how is Multidimensional arrays represented in C++, how to access the elements in the Multidimensional array.
What is a Multidimensional Array?
A Multidimensional array is an array of arrays.
How are Multidimensional Arrays represented in C++
Suppose a programmer wants to represent the two-dimensional array Exforsys as an array with three rows and four columns all having integer elements. This would be represented in C++ as:
int Exforsys[3][4];
It is represented internally as:
Exforsys
Data Type: int
How to access the elements in the Multidimensional Array
Exforsys
Data Type: int
Highlighted cell represent Exforsys[1][2]
Based on the above two-dimensional arrays, it is possible to handle multidimensional arrays of any number of rows and columns in C++ programming language. This is all occupied in memory. Better utilization of memory must also be made.
Multidimensional Array Example:
#include <iostream.h>
const int ROW=4;
const int COLUMN =3;
void main()
{
int i,j;
int Exforsys[ROW][COLUMN];
for(i=0;i<ROWS;i++)
for(j=0;j<COLUMN;J++)
{
cout << "Enter value of Row "<<i+1;
cout<<",Column "<<j+1<<":";
cin>>Exforsys[i][j];
}
cout<<"\n\n\n";
cout<< " COLUMN\n";
cout<< " 1 2 3";
for(i=0;i<ROW;i++)
{
cout<<"\nROW "<<i+1;
for(j=0;j<COLUMN;J++)
cout<<Exforsys[i][j];
}
|
The output of the above program is
Enter value of Row 1, Column 1:10
Enter value of Row 1, Column 2:20
Enter value of Row 1, Column 3:30
Enter value of Row 2, Column 1:40
Enter value of Row 2, Column 2:50
Enter value of Row 2, Column 3:60
Enter value of Row 3, Column 1:70
Enter value of Row 3, Column 2:80
Enter value of Row 3, Column 3:90
Enter value of Row 4, Column 1:100
Enter value of Row 4, Column 2:110
Enter value of Row 4, Column 3:120
COLUMN
1 2 3
ROW 1 10 20 30
ROW 2 40 50 60
ROW 3 70 80 90
ROW 4 100 110 120
In the above example, the keyword const (specifying constant) precedes the data type that specifies the variable ROW and COLUMN to remain unchanged in value throughout the program. This is used for defining the array Exforsys ROW size and COLUMN size, respectively.
Trackback(0)
|