简体   繁体   中英

Printing numbers in zigzag order in 2 D array

#include <stdio.h>

int main(){
     int i,j;

    int flag = 0;
    int x [3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    for (i = 0;i<3;i++){
        if (flag ==1){

            for (j=2;j<0;j--){
                printf(" %d",x[i][j]);

            }
            flag =0;
        }
        else  {
            for (j=0;j<3;j++)
            {
                printf(" %d ",x[i][j]);
            }
            flag =1;
        }
    }
    return 0;
}

i'm trying to print the numbers in the array in a zigzag form the expected output should be 123654789 but all i got 123789 for some reason i dont enter the loop in the flag condition i want to know the reason.. thanks in advance

Instead of

        for (j=2;j<0;j--){

use

        for (j=2;j>-1;j--){

and (only for the nice formatting) instead of

            printf(" %d ",x[i][j]);

(near the end, with a space after %d ) use

            printf(" %d",x[i][j]);

(without that space).

Try this, it will give you the output what you want.

#include <stdio.h>

int main(){
    int i,j;

    int flag = 0;
    int x [3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    for (i = 0;i<3;i++){
        if (flag ==1){
            for (j=2;!(j<0);j--){
               printf(" %d",x[i][j]);
            }
        flag =0;
        } else  {
            for (j=0;j<3;j++) {
                printf(" %d",x[i][j]);
            }
            flag =1;
            }
        }
    return 0;
}

Output:

./a.out 1 2 3 6 5 4 7 8 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM