编写代码以在波形打印中打印矩阵的数字

问题描述 投票:0回答:1

i want the output to be 7 4 1 2 5 8 9 6 3 but the output is coming out to be
1 4 7 2 5 8 3 6 9
how can i fix it and what's the logic behind it so that i can print thr reverse wave print too

#include<stdio.h>

int main() {
    int m;
    printf("enter no. of rows of 1st matrix:");
    scanf("%d", &m);

    int n;
    printf("enter no. of columns of 1st matrix:");
    scanf("%d", &n);

    int a[m][n];

    printf("\n enter the elements of 1st matrix");
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    // wave print
     for(int j = 0; j < n; j++) {
        if(n % 2 == 0) {
            for(int i = 0; i < m-1; i++){
                printf("%d ", a[i][j]);
            }
        }
        else {
            for(int i = 0 - 1; i<=n-1; i++) {
                printf("%d ", a[i][j]);
            }
        }
        printf("\n");
    }

    return 0;
}
arrays c 2d
1个回答
0
投票

这个条件

if(n % 2 == 0) 

没有意义。相反,您需要检查变量

j

if(j % 2 == 0) 

如果

j
是偶数,那么相应的列必须从下到上输出。

您也可以仅使用一个内部 for 循环。

这是一个演示程序。

#include <stdio.h>

int main( void )
{
    enum { m = 3, n = 3 };
    int a[m][n] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    for (size_t i = 0; i < n; i++)
    {
        size_t even = i % 2 == 0, top = 0, bottom = m;

        for (size_t j = even ? bottom : top; j != (even ? top : bottom ); )
        {
            printf( "%d ", even ? a[--j][i] : a[j++][i] );
        }
    }

    putchar( '\n' );
}

程序输出为

7 4 1 2 5 8 9 6 3
© www.soinside.com 2019 - 2024. All rights reserved.