-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Wednesday, 12 August 2015

Two-dimensional arrays in C++

Definition

In C++ Two Dimensional array in C++ is an array that consists of more than one rows and more than one column. In 2-D array each element is refer by two indexes. Elements stored in these Arrays in the form of matrices. The first index shows a row of the matrix and the second index shows the column of the matrix.

Syntax

data type name of array[no. of rows][no. of columns] 

For example,

int item[4][5];

Accessing each location


In order to store values in a C++ two dimensional arrays the programmer have to specified the number of row and the number of column of a matrix. To access each individual location of a matrix to store the values the user have to provide exact number of row and number of column.

Example:

int matrix[2][2];

matrix[0][0]=20;

matrix[0][1]=25;

matrix[1][0]=30;

matrix[1][1]=35;

Entering data

Nested loop is used to enter data in 2-D arrays. It depends upon the programmer which loop he wants to use it could be While loop or it could be a For loop. The outer loop acts as the number of rows of a matrix and the inner loop acts as the number of columns of a matrix.

Example:















#include<iostream.h>
#include<conio.h>
main()
{
int matrix [5] [5];
for (int m1=0 ; m1<5 ; m1++)
{
for (int m2=0 ; m2<5 ; m2++)
{
Matrix [m1] [m2] = 5 ;
}
}
getch();
}

                 Reference

The reference of this article has been taken from

No comments:

Post a Comment