C 程式在執行時初始化二維陣列


問題

透過執行時編譯計算陣列中所有元素的總和和乘積。

解決方案

二維陣列用於在需要儲存值表(或)在矩陣應用中使用的情況

語法如下 −

datatype array_ name [rowsize] [column size];

例如,int a[5] [5];

陣列中的元素數量 = 行大小 * 列大小 = 5*5 = 25

示例

以下是 C 程式,透過執行時編譯計算陣列中所有元素的總和和乘積 −

 線上演示

#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: 
");    for(i=0;i<2;i++){       for(j=0;j<3;j++){          printf("A[%d][%d] :",i,j);          scanf("%d",&A[i][j]);       }       printf("
");    }    for(i=0;i<2;i++){       for(j=0;j<3;j++){          printf("B[%d][%d] :",i,j);          scanf("%d",&B[i][j]);       }       printf("
");    }    //Calculating sum and printing output//    printf("Sum array is :
");    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("
");    }    //Calculating product and printing output//    printf("Product array is :
");    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("
");    } }

輸出

當執行以上程式時,將產生以下結果 −

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

更新於: 08-03-2021

318 瀏覽量

開啟你的 職業生涯

透過完成該課程獲取認證

開始學習
廣告