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

In ma trận theo mẫu rắn (snake pattern) trong C

Bài toán

In ma trận n×n theo mẫu rắn: hàng chẵn (0,2,4...) in trái→phải, hàng lẻ (1,3,5...) in phải→trái.

Ví dụ 4×4

Input:
100 99 98 97
93 94 95 96
92 91 90 89
85 86 87 88

Output: 100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85

In ma trận theo mẫu rắn (snake pattern) trong C

Thuật toán

For i = 0 đến M-1:
    If i%2==0: for j=0→N-1 print arr[i][j]
    Else:      for j=N-1→0 print arr[i][j]

Mã nguồn C

#include <stdio.h>
#define M 4
#define N 4

int main() {
    int arr[M][N] = {
        {100,99,98,97},
        {93,94,95,96},
        {92,91,90,89},
        {85,86,87,88}
    };
    for (int i=0; i=0; j--) printf("%d ", arr[i][j]);
    }
    return 0;
}

Kết quả

100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85