Tuesday, December 28, 2010

Addition of two matrices/matrix

/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/

/**
* program for addition of matrices
*/

#include<stdio.h>
void main()
{


int
ar = 0 , ac = 0 , i = 0 , j = 0 , br = 0 , bc = 0 ;

int
a[20][20] , b[20][20] , ans[20][20];

// scan the first array
printf("Enter no of rows in first matrix ? ");
scanf("%d",&ar);

printf("Enter no of columns in first matrix ? ");
scanf("%d",&ac);
if
(ar < 0 || ar>20 || ac < 0 || ac>20)
{


printf("Invalid number of rows or columns. It must be brtween 1 to 20");
}

else

{

// logic for scanning the numbers
for(i = 0 ; i < ar ;i++)
{


for
(j = 0 ; j < ac ; j++)
{


printf("Enter element [%d][%d]: ", i,j);
scanf("%d",&a[i][j]);
}
}


printf("Enter no of rows in second matrix ? ");
scanf("%d",&br);
printf("Enter no of columns in second matrix ? ");

scanf("%d",&bc);

// scan the second array
if(br < 0 || br>20 || bc < 0 || bc>20)
{


printf("Invalid number of rows or columns. It must be brtween 1 to 20");
}

else

{

// logic for scanning the numbers
for(i = 0 ; i < br ;i++)
{


for
(j = 0 ; j < bc ; j++)
{


printf("Enter element [%d][%d]: ", i,j);
scanf("%d",&b[i][j]);
}
}


if
((ar == br ) && (ac == bc))
{


for
( i = 0 ; i < ar ; i++)
{


for
(j = 0 ; j < ac ; j++)
{


ans[i][j] = a[i][j] + b[i][j];
}
}


printf("\nAddition of marices is:\n");
for
(i = 0 ; i < ar ; i++)
{


for
(j = 0 ; j < ac ; j++)
{


printf( "%d \t" , ans[i][j]);
}

printf("\n");
}
}


else

{

printf("\nNo of rows does not match no of columns. So addition is not possible");
}
}
}
}

No comments:

Post a Comment