Multi dimensional Arrays:
Where Single Dimensional Arrays has one column and multiple rows,
multi-dimensional arrays has multiple rows as well as multiple columns. Multi-dimensional
data structure also known as matrices. A multi-dimensional array with 3 rows
and 3 columns is shown. There are two array subscripts. One subscript denotes
the row & the other the column.
N[0][0]
|
N[0][1]
|
N[0][2]
|
N[1][0]
|
N[1][1]
|
N[1][2]
|
N[2][0]
|
N[2][1]
|
N[2][2]
|
Input a 3/3 Matrix, Print the sum of rows,
Columns, Left Diagonal and Right Diagonal.
#include <stdio.h>
#include <conio.h>
/*Input a 3/3 Matrix, Print the sum of rows, Columns, Left Diagonal and
Rigth Diagonal*/
void main()
{
int ar[3][3];
int
i,j,c,sr=0,sc=0,sld=0,srd=0;
clrscr();
for(i=0;i<3;i=i+1)
{
for(j=0;j<3;j=j+1)
{
printf("\n\tEnter
Element for [%d][%d] : ",i,j);
scanf("%d",&ar[i][j]);
}
}
//sum of row, column,
left diagonal, right diagonal
printf("\n\n");
for(i=0;i<3;i=i+1)
{
sr=sc=0;
for(j=0;j<3;j=j+1)
{
printf("%3d",ar[i][j]);
sr=sr+ar[i][j];
//row sum;
sc=sc+ar[j][i];
//column sum
if(i==j)
{
sld=sld+ar[i][j];//left
diagonal
}
if(i+j==2)
// 2 means n-1 right diagonal
{
srd=srd+ar[i][j];
}
}
printf("\tSum
of row %d Sum of column %d\n",sr,sc);
}
printf("\n\n\tSum
of left diagonal %d Sum of right diagonal %d\n ",sld,srd);
getch();
}
Input a 3/3 Matrix, and Transpose it.
#include <stdio.h>
#include <conio.h>
//Input a 3/3 Matrix, and Transpose it
void main()
{
int ar[3][3];
int i,j,c;
clrscr();
for(i=0;i<3;i=i+1)
{
for(j=0;j<3;j=j+1)
{
printf("\n\tEnter
Element for [%d][%d] : ",i,j);
scanf("%d",&ar[i][j]);
}
}
printf("\nOriginal
Array \n");
for(i=0;i<3;i=i+1)
{
for(j=0;j<3;j=j+1)
{
printf("%3d",ar[i][j]);
}
printf("\n");
}
//transpose in same
array
printf("\nAfter
Transpose\n");
for(i=0;i<3;i=i+1)
{
for(j=0;j<i;j=j+1)
{
c=ar[i][j];
ar[i][j]=ar[j][i];
ar[j][i]=c;
}
}
for(i=0;i<3;i=i+1)
{
for(j=0;j<3;j=j+1)
{
printf("%3d",ar[i][j]);
}
printf("\n");
}
getch();
}
No comments:
Post a Comment