C Program on two-dimensional array initialized at run time

CServer Side ProgrammingProgramming

Problem

Calculate the sum and product of all elements in an array by using the run-time compilation.

Solution

A two-dimensional array is used in situations where a table of values have to be stored (or) in matrices applications

The syntax is as follows −

datatype array_ name [rowsize] [column size];

For example, int a[5] [5];

Number of elements in array = rowsize *columnsize = 5*5 = 25

Example

Following is the C program to calculate the sum and product of all elements in an array by using the run-time compilation −

 Live Demo

#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
   //Reading elements into the array's A and B using for loop//
   printf("Enter elements into the array A: \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] :",i,j);
         scanf("%d",&A[i][j]);
      }
      printf("\n");
   }
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("B[%d][%d] :",i,j);
         scanf("%d",&B[i][j]);
      }
      printf("\n");
   }
   //Calculating sum and printing output//
   printf("Sum array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         sum[i][j]=A[i][j]+B[i][j];
         printf("%d\t",sum[i][j]);
      }
      printf("\n");
   }
   //Calculating product and printing output//
   printf("Product array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         product[i][j]=A[i][j]*B[i][j];
         printf("%d\t",product[i][j]);
      }
      printf("\n");
   }
}

Output

When the above program is executed, it produces the following result −

Enter elements into the array A:
A[0][0] :12
A[0][1] :23
A[0][2] :03

A[1][0] :25
A[1][1] :34
A[1][2] :01

B[0][0] :03
B[0][1] :46
B[0][2] :23

B[1][0] :01
B[1][1] :24
B[1][2] :32

Sum array is:
15    69    26
26    58    33
Product array is:
36    1058   69
25    816    32
raja
Published on 08-Mar-2021 06:18:38
Advertisements