Computer Concept & Programming In C - Unit IV - 3

Q.5. What do you mean by two dimensional array? Write a program to compute the sum of diagonal elements of square matrix.                                           (AKTU. 2011 - 12)
Ans. Two dimensional array is an array of one dimensional array.
# include <stdio.h>
# include <conio.h>
# define n 3
void main ( )
{
   int i, j;
  float a[n][n], sum;
  clrscr ( );
  printf(“\n Enter the elements”);
 for(i=0; i<n; i++)
   for(j=0; j<n; j++)
     {
printf(“\n Enter a[%d][%d]=”,i,j);
scanf(“%f”, &a[i][j]);
     }
// Computing sum of diagonal elements
sum = 0.0;
for(i=0; i<n; i++)
   for(j=0; j<n; j++)
    {
if(i==j)
     sum += a[i][j];
    }
printf(“\n sum of diaginal = %f”, sum);
getch ( );
}
Sum of diagonal can also be computed by single loop.
i.e.
for(i=0; i<n; i++)
sum += a[i][i];

Q.6 Write a progam in C to multiply two matrices. Take the size and element of matrices through keyboard.                              (AKTU. 2009-10)
Ans.
#include<stdio.h>
#include<conio.h>
#define n 3
void main()
{
  int i, j, k;
  int r1, c1, r2, c2;
  float a[n][n], b[n][n], c[n][n];

  clrscr();
  printf("\nMatrix Multiplication Using Static Memory Allocation");
  printf ("\n Suitable for 3 X 3 matrices");
  printf("\nComputes AB = C ");

  printf("\nRows in A = ?\n");
  scanf("%d",&r1);
  printf("\nColumns in A = ?\n");
  scanf("%d",&c1);

  printf("\nRows in B = ?\n");
  scanf("%d",&r2);
  printf("\nColumns in B = ?\n");
  scanf("%d",&c2);

   //Matrix Multiplication Compatibility check
 if((r1 > 0) && (c1 > 0) && (r2 > 0) && (c2 > 0) && (c1 == r2))
   {
     printf("\Enter the elements of the array  a:");
  for( i = 0; i < r1; i++)
     for(j = 0; j < c1; j++)
{
  printf("\nEnter a[%d][%d] = ",i, j);
  scanf("%f",&a[i][j]);
};
     printf("\Enter the elements of the array  b:");
  for( i = 0; i < r2; i++)
     for(j = 0; j < c2; j++)
{
  printf("\nEnter b[%d][%d] = ",i, j);
  scanf("%f",&b[i][j]);
};
   // Initializing C
  for( i = 0; i < r1; i++)
     for(j = 0; j < c2; j++)
  c[i][j] = 0.0;

  // Multiplication
  for( i = 0; i < r1; i++)
     for(j = 0; j < c2; j++)
for(k = 0; k < c1; k++)
   c[i][j] = c[i][j] + a[i][k] *  b[k][j];

 //Output
 clrscr();
 printf("\nMatrix Multiplication C = A.B");
 printf("\n Product C :");
  for( i = 0; i < r1; i++)
     for(j = 0; j < c2; j++)
{
  printf("\n c[%d][%d] = ",i, j);
  printf("%f", c[i][j]);
};
   }
    else
       printf("\n Matrices Incompatible for Multiplication. Press any key.");
    getch();
}