Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

การพิมพ์องค์ประกอบมุมและผลรวมในเมทริกซ์ 2-D ในโปรแกรม C


ได้รับอาเรย์ขนาด 2X2 ท้าทายคือพิมพ์ผลรวมขององค์ประกอบมุมทั้งหมดที่เก็บในอาเรย์

สมมติเมทริกซ์ mat[r][c] มีแถว "r" และคอลัมน์ "c" เริ่มจาก 0 องค์ประกอบมุมคือ mat[0][0], mat[0][c-1], mat[r-1][0], mat[r-1][c-1] หาผลรวมและพิมพ์

ตัวอย่าง

Input: Enter the matrix elements :
10 2 10
2 3 4
10 4 10
Output: sum of matrix is : 40

การพิมพ์องค์ประกอบมุมและผลรวมในเมทริกซ์ 2-D ในโปรแกรม C

อัลกอริทึม

START
Step 1-> create macro for rows and column as #define row 3 and #define col 3
Step 2 -> main()
  Declare int sum=0 and array as a[row][col] and variables int i,j,n
  Loop For i=0; i<3; i++
    Loop For j=0; j<3; j++
      Input a[i][j]
    End
  End
  Print a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1]
STOP

ตัวอย่างโค้ด C

#include
#define row 3
#define col 3
int main(){
    int sum=0,a[row][col],i,j,n;
    printf("Enter the matrix elements : ");
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            scanf("%d",&a[i][j]);
        }
    }
    printf("sum of matrix is : %d",a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] );
    return 0;
}

ผลลัพธ์

การรันโปรแกรมจะได้ผลลัพธ์ดังนี้:

Enter the matrix elements : 10 2 10 2 3 4 10 4 10
sum of matrix is : 40