Thursday, January 23, 2014

Printing pattern 8

1
2   7
3   8 12
4   9 13 16
5 10 14 17 19
6 11 15 18 20 21

Seeing the pattern we can figure our that 1st element of each line is the value of line no. that is dependent on i (outer loop variable)

Some further look into the pattern reveals the following
1
2 7(2+5)
3 8(3+5) 12(8+4)
4 9(4+5) 13(9+4) 16(13+3)
5 10(5+5) 14 (10+4) 17(14+3) 19(17+2)
and so on.

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

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

            if(j>1)
            {
                printf("%2d ",curval);
                fix--;
                curval=curval+fix;
            }
        }
        printf("\n");
    }
    return 0;
}

No comments:

Post a Comment