ปัญหา
มาเขียนโปรแกรม C เพื่อคำนวณผลรวมแถวและผลรวมคอลัมน์ของอาร์เรย์ 5 x 5 โดยใช้การรวบรวมรันไทม์
วิธีแก้ปัญหา
ในโปรแกรมนี้ เรากำลังป้อนค่าของอาร์เรย์ที่มีขนาด 5X5 เมทริกซ์ระหว่างรันไทม์ในคอนโซล โดยใช้ for loops เรากำลังพยายามเพิ่มแถวและคอลัมน์
ตรรกะสำหรับการทำผลรวมแถวแสดงไว้ด้านล่าง -
for(i=0;i<5;i++) {//I is for row
for(j=0;j<5;j++){ //j is for column
row=row+A[i][j]; //compute row sum
} ตรรกะสำหรับการทำผลรวมคอลัมน์คือ -
for(j=0;j<5;j++){ // j is for column
for(i=0;i<5;i++){ //I is for row
column=column+A[i][j];
} ตัวอย่าง
#include<stdio.h>
void main(){
//Declaring array and variables//
int A[5][5],i,j,row=0,column=0;
//Reading elements into the array//
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]);
}
}
//Computing sum of elements in all rows//
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;
}
//Computing sum of elements in all columns//
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;
}
} ผลลัพธ์
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