Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

puzzle

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?

like image 973
Shubham Avatar asked Apr 11 '12 11:04

Shubham


4 Answers

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);
}
like image 84
user1202136 Avatar answered Nov 20 '22 14:11

user1202136


for (int i=0; i<1; i++)
{
    std::cout << "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1"
}
like image 29
FireAphis Avatar answered Nov 20 '22 13:11

FireAphis


How about this:

std::string first;
std::string second;

for ( int i = 1 ; i <= 15 ; i++ )
{
   std::ostringstream s;
   s << i;
   first += s.str();
   second = s.str() + second;
}

std::cout << first << second;
like image 8
Luchian Grigore Avatar answered Nov 20 '22 15:11

Luchian Grigore


Alternative:

static int bla[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

for (int i = 0; i < 30; i++) 
{        
    printf("%d\n", bla[i]);
}

The good one, it is faster in execution as compare to all ...

like image 5
ouah Avatar answered Nov 20 '22 13:11

ouah