Program for addition of matrices


C File =>


/* Write a program to add two matrices and display the result. Use dynamic memory allocation.*/


#include<stdio.h>
#include<stdlib.h>
int main()
{
       int n,i,j,*ptr[50],*ptr1[50],sum[50][50];
       printf("\n Enter order of matrix : ");
       scanf("%d",&n);
     //Dynamic allocation of memory
      for(i=0;i<n;i++)
     {
        ptr[i]=(int*)malloc(n*sizeof(int));
        ptr1[i]=(int*)malloc(n*sizeof(int));
     }
    // Accepting matrix
    for(i=0;i<n;i++)
   {
     for(j=0;j<n;j++)
    {
       printf("\n Enter matrix element a%d%d : ",i+1,j+1);
       scanf("%d",&ptr[i][j]);
     }
   }
   printf("\n\n Given Matrix1 is : \n ");
   for(i=0;i<n;i++)
  {
     for(j=0;j<n;j++)
           printf("%d\t",ptr[i][j]);
     printf("\n");
   }
   for(i=0;i<n;i++)
  {
   for(j=0;j<n;j++)
  {
     printf("\n Enter Matrix2 element b%d%d : ",i+1,j+1);
     scanf("%d",&ptr1[i][j]);
   }
 }
  printf("\n\n Given Matrix2 is : \n ");
  for(i=0;i<n;i++)
 {
    for(j=0;j<n;j++)
        printf("%d\t",ptr1[i][j]);
    printf("\n");
  }

// Calculating sum
  for(i=0;i<n;i++)
 {
    for(j=0;j<n;j++)
   {
        sum[i][j]=ptr[i][j]+ptr1[i][j];
    }
  }
  printf("\n Resultant matrix :\n");
  for(i=0;i<n;i++)
 {
    for(j=0;j<n;j++)
       printf("%d\t",sum[i][j]);
    printf("\n");
  }
 return 0;
}

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.