Wednesday, April 11, 2012

C/C++ Puzzle: To print values from 1..15 15..1 with a single for loop

It was given by my colleague, to print values 1 2 3 4 .... 15 15 ..... 4 3 2 1 with only one for loop, no functions, no goto statements and without the use of any conditional statements or ternary operators.


So I employed typecasting to solve it, but it is not an exact solution since 15 is not printed twice.


int main()
 {
     int i, j;
     for(i = 1, j = 0;j < 29;j++, i += int(j/15)*-2 + 1)
         cout<<i<<endl;
 }
 


Output: 1 2 3 4 ... 15 14 13 .... 2 1


Any alternative solutions?



Answer:

You can loop from 1 to 30, then use the fact that (i/16) will be "0" for your ascending part and "1" for your descending part.
for (int i = 1; i < 31; i++)
{
    int number = (1-i/16) * i + (i/16) * (31 - i);
    printf("%d ", number);
}

No comments:

Post a Comment