0
#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

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

2 Answers2

1

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).

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • Please consider to accept my answer (click on the check mark) if it was useful for you (2 reputation for you). – MarianD Apr 03 '17 at 19:48
0

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

danglingpointer
  • 4,708
  • 3
  • 24
  • 42