You are on page 1of 11

2D

Array
Eng Fadia M Hasen
2D Array

Two Dimensional Array in C++


In C++, a two-dimensional array is a grouping of elements arranged in
rows and columns. Each element is accessed using two indices: one for
the row and one for the column, which makes it easy to visualize as a
table or grid.
2D Array

Syntax of 2D Array
data_Type array_name[n][m];
Where, 2D Array
n: Number of rows.
m: Number of columns
2D Array

Syntax of 2D Array
data_Type array_name[n][m];
Where, 2D Array
n: Number of rows.
m: Number of columns
2D Array

int x[3][3]; or

Declaring and
Creating Arrays int x[3][3]={12,3,4,54,7,83,86,11,65};

Int x[3][3]={{1,2,3},{54,7,83},{86,11,65}};
2D Array Example

Write Program to Read and Print 4*5 Array


#include<iostream>
main()
{ int x[4][5],i,j;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
cin>>x[i][j];
cout<<"\n\n";
for(i=0;i<4;i++)
{for(j=0;j<5;j++)
{cout<<x[i][j]<<"\t";}
cout<<"\n";} }
2D Array

Properties of 2D Array whose number of rows is


equal to the number of columns
2D Array

Properties of 2D Array whose number of rows is


equal to the number of columns

• Main diameter: row number equal to column number) i==j)


• Secondary diameter : (i+j==n-1).
• Elements above the main diagonal The column value is greater
than the row value(j>i).
• Items under the main diameter of the column value is smaller
than the row value(j<i).
• Elements above the secondary diameter(i+j<n-1).
• Elements under the secondary diameter(i+j>n-1).
2D Array Example
Program to read and print a 5*5 matrix after zeroing the main
diameter elements
#include<iostream>
main()
{ int x[5][5],i,j;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
cin>>x[i][j];
cout<<"\n\n";
for(i=0;i<5;i++)
{for(j=0;j<5;j++)
{if(i==j) cout<<"0"<<"\t";
else cout<<x[i][j]<<"\t";}
cout<<"\n";} }
2D Array Example

Square matrix (5*5) Sum the elements above the main diagonal
and Sum the elements below it and Sum the elements above the
diameter Secondary and below it separately
2D Array
#include<iostream> for(i=0;i<5;i++)
using namespace std; for(j=0;j<5;j++) {
int main() if(i<j)
{int sum+=a[i][j];
i,j,sum,sum1,sum2,sum3; if(i>j)
sum=sum1=sum2=sum3=0; sum1+=a[i][j];
int a[5][5]; if((i+j)<4)
for(i=0;i<5;i++) sum2+=a[i][j];
for(j=0;j<5;j++) if((i+j)>4)
cin>>a[i][j]; sum3+=a[i][j];}
cout<<"\n sum above secondary diagonal=
for(i=0;i<5;i++) "<<sum2;
{for(j=0;j<5;j++) cout<<"\n sum above main diagonal= "<<sum;
cout<<"\n sum under main diagonal= "<<sum1;
{cout<<a[i][j]<<"\t";} cout<<"\n sum under secondary diagonal=
cout<<"\n";} "<<sum3;}

You might also like