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

โปรแกรม C สร้าง Identity Matrix

Identity Matrix ขนาด n×n: แนวทแยงมุมเป็น 1 ที่เหลือเป็น 0

ตัวอย่าง n=4

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

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

#include <stdio.h>

void identity(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%d ", (i == j) ? 1 : 0);
        printf("\n");
    }
}

int main() {
    identity(4);
    return 0;
}

ผลลัพธ์

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1