Search code examples
cloops

A tough loop in a contest


Today I got a irritating question in a coding contest. I creamed through the first round but in the second round the following question got me in a trap.

Question: Input N = 4
          Output:
                 1
                 0 1
                 1 0 1
                 0 1 0 1

I tried many things but every time I failed.

Apart from this stupid wrong solution I tried many fancy stuff and failed in the end. What part of my C knowledge is weak?

If you were given this question how would you solve it?


Solution

  • This did the job for me.

    int i,j,flag;
    int num=4;
    
    flag=1;
    for(i=0;i<num;i++)
    {
        for(j=0;j<i+1;j++)
        {
                printf("%d",(j+flag)%2);
        }
        if(flag)
        {
                flag=0;
        }
        else
        {
                flag=1;
        }
        printf("\n");
    
     }