Computer >> Máy Tính >  >> Lập trình >> lập trình C

Tính tổng của tất cả các phần tử trong mảng 2 D trong C

Vấn đề

Tính tổng tất cả các phần tử của mảng hai chiều bằng cách sử dụng khởi tạo thời gian chạy.

Giải pháp

Mảng hai chiều được sử dụng trong các trường hợp cần lưu trữ một bảng giá trị (hoặc) trong các ứng dụng ma trận

Cú pháp như sau -

datatype array_ name [rowsize] [column size];

Ví dụ:int a [4] [4];

Số phần tử trong một mảng =rowize * columnize =4 * 4 =16

Ví dụ

Sau đây là chương trình C để tính tổng tất cả các phần tử của mảng hai chiều bằng cách sử dụng khởi tạo thời gian chạy -

#include<stdio.h>
void main(){
   //Declaring array and variables//
   int A[4][3],i,j,even=0,odd=0;
   //Reading elements into the array//
   printf("Enter elements into the array A :\n");
   for(i=0;i<4;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] : ",i,j);
         scanf("%d",&A[i][j]);
      }
   }
   //Calculating sum of even and odd elements within the array using for loop//
   for(i=0;i<4;i++){
      for(j=0;j<3;j++){
         if((A[i][j])%2==0){
            even = even+A[i][j];
         }
         else{
            odd = odd+A[i][j];
         }
      }
   }
   printf("Sum of even elements in array A is : %d\n",even);
   printf("Sum of odd elements in array A is : %d",odd);
}

Đầu ra

Khi chương trình trên được thực thi, nó tạo ra kết quả sau -

Enter elements into the array A:
A[0][0] : 01
A[0][1] : 02
A[0][2] : 03
A[1][0] : 04
A[1][1] : 10
A[1][2] : 20
A[2][0] : 30
A[2][1] : 40
A[2][2] : 22
A[3][0] : 33
A[3][1] : 44
A[3][2] : 55
Sum of even elements in array A is: 172
Sum of odd elements in array A is: 92