Custom Search

Saturday, 16 April 2011

Program to read two matrices and print addition & subtraction of the matrices through array, Matrices Addition & Subtraction in single program


Program to read two matrices and print addition & subtraction of the matrices through array, Matrices Addition & Subtraction in single program 

Program

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,r1,c1,r2,c2,a[10][10], b[10][10], c[10][10];
clrscr();
printf("Enter the rows & column of 1st matrices:\n");
scanf("%d %d",&r1, &c1 );
printf("\nEnter the rows & column of 2nd matrices:\n");
scanf("%d %d",&r2, &c2);
if((r1==r2)&&(c1==c2))
{
printf("\nMatrices addition is possible\n");
}
else
{
printf("\nMatrices addition is not possible\n");
exit(0);
}
printf("\nEnter the first matrices:\n");
for(i=0;i<r1;i++)
{
 for(j=0;j<c1;j++)
 {
 scanf("%d",&a[i][j]);
 }
}
printf("\nFirst Matrices is:\n");
 for(i=0;i<r1;i++)
{
 printf("\n");
 for(j=0;j<c1;j++)
 {
 printf("%d\t",a[i][j]);
 }
}
printf("\n");
printf("\nEnter second Matrices:\n");
for(i=0;i<r2;i++)
{
 for(j=0;j<c2;j++)
 {
 scanf("%d",&b[i][j]);
 }
}
printf("\nSecond Matrices is:\n");
for(i=0;i<r2;i++)
{
 printf("\n");
 for(j=0;j<c2;j++)
 {
 printf("%d\t",b[i][j]);
 }
}
printf("\n");
printf("\nMatrices addition is:\n");
for(i=0;i<r1;i++)
{
 printf("\n");
 for(j=0;j<r2;j++)
 {
 c[i][j] = a[i][j] + b[i][j];
 printf("%d\t",c[i][j]);
 }
}
printf("\n");
printf("\nMatrices subtraction is:\n");
 for(i=0;i<r1;i++)
 {
 printf("\n");
 for(j=0;j<r2;j++)
 {
 c[i][j] = a[i][j] - b[i][j];
 printf("%d\t", c[i][j]);
 }
}
getch();
}

Changes for C++
If you want to write the same program in c++ apply the following changes to the program.
1.) change the header file from "#include<stdio.h>" to "#include<iostream>.h" 
2.)  for input & output use "cout<<" & "cin>>" instead of "printf" & "scanf".
3.) don't use "% "symbol and "&" sign in "cin>>" statement.

Click here to check the output

No comments:

Post a Comment

Laptops