首頁  >  文章  >  後端開發  >  在C程式設計中,在運行時使用二維數組進行工作

在C程式設計中,在運行時使用二維數組進行工作

WBOY
WBOY轉載
2023-09-13 23:29:071331瀏覽

在C程式設計中,在運行時使用二維數組進行工作

問題

寫一個C程序,使用執行時間編譯來計算二維數組中所有元素的和與積。

解決方案

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

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

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

在這個程式中,我們將在運行時計算二維數組所有元素的總和以及所有元素的乘積。

邏輯用於計算二維陣列中所有元素的總和-

printf("Sum array is : </p><p>");
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("</p><p>");
}

計算二維陣列中所有元素乘積的邏輯−

printf("Product array is : </p><p>");
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("</p><p>");
}
}

Example

 實例示範

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

輸出

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

以上是在C程式設計中,在運行時使用二維數組進行工作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除