여기에서 행렬 요소를 Z 형식으로 인쇄하는 방법을 살펴보겠습니다. 따라서 배열이 아래와 같으면 -
5 8 7 1 2 3 6 4 1 7 8 9 4 8 1 5
그러면 다음과 같이 인쇄됩니다:5, 8, 7, 1, 6, 7, 4, 8, 1, 5
알고리즘
printMatrixZ(매트)
Begin print the first row i := 1, j := n-2 while i < n and j >= 0, do print mat[i, j] i := i + 1, j := j - 1 done print the last row End
예시
#include<iostream>
#define MAX 4
using namespace std;
void printMatrixZ(int mat[][MAX], int n){
for(int i = 0; i<n; i++){
cout << mat[0][i] << " ";
}
int i = 1, j = n-2;
while(i < n && j >= 0){
cout << mat[i][j] << " ";
i++;
j--;
}
for(int i = 1; i<n; i++){
cout << mat[n-1][i] << " ";
}
}
main() {
int matrix[][MAX] = {{5, 8, 7, 1},
{2, 3, 6, 4},
{1, 7, 8, 9},
{4, 8, 1, 5}
};
printMatrixZ(matrix, 4);
} 출력
5 8 7 1 6 7 4 8 1 5