📜  C ++程序以Z形式打印矩阵

📅  最后修改于: 2021-05-31 18:12:30             🧑  作者: Mango

给定n * n阶方阵,我们需要以Z形式打印矩阵的元素

Examples:
Input : mat[][] =  {1, 2, 3,
                    4, 5, 6,
                    7, 8, 9}
Output : 1 2 3 5 7 8 9

Input : mat[][] = {5, 19, 8, 7,
                   4, 1, 14, 8,
                   2, 20, 1, 9,
                   1, 2, 55, 4}
Output: 5 19 8 7 14 20 1 2 55 4
// CPP program to print a square matrix in Z form
#include 
using namespace std;
const int MAX = 100;
  
// Function to print a square matrix in Z form
void printZform(int mat[][MAX], int n)
{
    // print first row
    for (int i = 0; i < n; i++)
        cout << mat[0][i] << " ";
  
    // Print diagonal
    int i = 1, j = n - 2;
    while (i < n && j >= 0) // print diagonal
    {
        cout << mat[i][j] << " ";
        i++;
        j--;
    }
  
    // Print last row
    for (int i = 1; i < n; i++)
        cout << mat[n - 1][i] << " ";
}
  
// Driver function
int main()
{
    int mat[][MAX] = { { 4, 5, 6, 8 },
                       { 1, 2, 3, 1 },
                       { 7, 8, 9, 4 },
                       { 1, 8, 7, 5 } };
    printZform(mat, 4);
    return 0;
}
输出:
4 5 6 8 3 8 1 8 7 5

请参阅有关以Z格式打印矩阵的程序的完整文章,以获取更多详细信息!

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”