Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Tính tổng hàng và cột ma trận bằng C


Vấn đề

Viết chương trình C tính tổng hàng và cột của mảng 5x5 tại runtime.

Giải pháp

Nhập giá trị mảng 5x5 lúc runtime, dùng vòng lặp for tính tổng hàng và cột.

Logic tổng hàng:

for(i=0;i<5;i++) {//i cho hàng     for(j=0;j<5;j++){ //j cho cột         row=row+A[i][j]; //tính tổng hàng     }

Logic tổng cột:

for(j=0;j<5;j++){ //j cho cột     for(i=0;i<5;i++){ //i cho hàng         column=column+A[i][j];     }

Ví dụ

#include<stdio.h> void main(){     //Khai báo mảng và biến//     int A[5][5],i,j,row=0,column=0;     //Nhập phần tử//     printf("Enter elements into the array : \n");     for(i=0;i<5;i++){         for(j=0;j<5;j++){             printf("A[%d][%d] : ",i,j);             scanf("%d",&A[i][j]);         }     }     //Tính tổng các hàng//     for(i=0;i<5;i++){         for(j=0;j<5;j++){             row=row+A[i][j];         }         printf("The sum of elements in row number %d is : %d\n",i,row);         row=0;     }     //Tính tổng các cột//     for(j=0;j<5;j++){         for(i=0;i<5;i++){             column=column+A[i][j];         }         printf("The sum of elements in column number %d is : %d\n",i,column);         column=0;     } }

Kết quả

Enter elements into the array : A[0][0] : A[0][1] : A[0][2] : A[0][3] : A[0][4] : A[1][0] : A[1][1] : A[1][2] : A[1][3] : A[1][4] : A[2][0] : A[2][1] : A[2][2] : A[2][3] : A[2][4] : A[3][0] : A[3][1] : A[3][2] : A[3][3] : A[3][4] : A[4][0] : A[4][1] : A[4][2] : A[4][3] : A[4][4] : The sum of elements in row number 0 is : 0 The sum of elements in row number 1 is : 9 The sum of elements in row number 2 is : -573181070 The sum of elements in row number 3 is : 4196174 The sum of elements in row number 4 is : -417154028 The sum of elements in column number 5 is : -994596681 The sum of elements in column number 5 is : 65486 The sum of elements in column number 5 is : 1 The sum of elements in column number 5 is : 4196182 The sum of elements in column number 5 is : 4196097