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

โปรแกรมพิมพ์เมทริกซ์สี่เหลี่ยมจัตุรัสแบบ Z-form ในภาษา C

คำอธิบายโปรแกรม

พิมพ์สมาชิกของเมทริกซ์สี่เหลี่ยมจัตุรัสในรูปแบบ Z

เมทริกซ์สี่เหลี่ยมจัตุรัส (Square Matrix) คือเมทริกซ์ที่มีจำนวนแถวและคอลัมน์เท่ากัน เมทริกซ์ n×n เรียกว่าเมทริกซ์สี่เหลี่ยมจัตุรัสขนาด n

อัลกอริทึม

เพื่อพิมพ์สมาชิกของเมทริกซ์สี่เหลี่ยมจัตุรัสแบบ Z form เราต้องพิมพ์แถวแรก แล้วเส้นทแยงมุม แล้วแถวสุดท้ายของเมทริกซ์สี่เหลี่ยมจัตุรัส

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

/* Program to print a square matrix in Z form */
#include <stdio.h>

int main() {
    int rows, cols, r, c, matrix[10][10];
    // clrscr();
    printf("Please enter the number of rows for the Square matrix: ");
    scanf("%d", &rows);
    printf("\n");
    printf("Please enter the number of columns for the Square matrix: ");
    scanf("%d", &cols);
    printf("\n");
    printf("Please enter the elements for the Matrix: \n");
    for (r = 0; r < rows; r++) {
        for (c = 0; c < cols; c++) {
            scanf("%d", &matrix[r][c]);
        }
    }
    printf("The Z Form Elements in the Square Matrix are: \n");
    // แถวแรก
    for (r = 0; r < rows; r++) {
        printf("%d\t ", matrix[0][r]);
    }
    // เส้นทแยงมุม
    for (r = 1, c = cols - 2; r < cols && c >= 0; r++, c--) {
        printf("%d\t ", matrix[r][c]);
    }
    // แถวสุดท้าย
    for (r = 1; r < cols; r++) {
        printf("%d\t ", matrix[cols - 1][r]);
    }
    // getch();
    return 0;
}

เอาต์พุต

แสดงสมาชิกของเมทริกซ์สี่เหลี่ยมจัตุรัสในรูปแบบ Z