Thursday, January 23, 2014

Printing Pattern 9

1
01
101
0101
10101

Alternating between 1 and 0. Hmm! We can use number%2 that will always be 1 or 0. % means remainder division(or modular division) and gives remainder when number is divided by another number. When a number is divided by number 'n', remainder is always between 0 and n-1. So in case of division with 2, remainder is between 0 to 1 (n-1).
0 and 1 keeps on alternating in each line as well as for the next line. How about making it dependent on line both i and j say sum of i and j

line 1 element 1 -- i=1,j=1, i+j=2, 2%2=0 but we want a 1 instead. So add 1 to i+j and then mod it will 2.
Then i (outer loop variable) loops 5 times and j (inner loop variable) loops from 1 till i for each line and then goes to the next line.

i     j    i+j+1     i+j+1%2
1    1      3              1
next line
2    1      4              0
2    2      5              1
next line
3    1      5              1
3    2      6              0
3    3      7              1
next line
and so on.

#include<stdio.h>
int main()
{
     int i,j;

    for(i=1;i<=5;i++)
    {
          for(j=1;j<=i;j++)
                 printf("%d",(i+j+1)%2);

          printf("\n");
    }

    return 0;
}

 

No comments:

Post a Comment