在C語言程式的執行時使用二維陣列


問題

使用執行時編譯編寫一個C程式,計算二維陣列中所有元素的和和乘積。

解決方案

  • 執行時編譯或初始化也稱為動態分配。在執行時(執行時)分配記憶體稱為動態記憶體分配。

  • 函式calloc()和malloc()支援分配動態記憶體。

在這個程式中,我們將計算在執行時二維陣列中所有元素的和和乘積。

計算2D陣列中所有元素和的邏輯 -

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("
"); }

計算2D陣列中所有元素乘積的邏輯 -

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("
"); } }

範例

 現場演示

#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] :A[0][1] :A[0][2] :
A[1][0] :A[1][1] :A[1][2] :
B[0][0] :B[0][1] :B[0][2] :
B[1][0] :B[1][1] :B[1][2] :
Sum array is :
000
000
Product array is :
000
000

更新於:2021-3-9

1K+瀏覽

開啟你的職業生涯

完成課程以獲得證書

開始
廣告
© . All rights reserved.