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?
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);
}
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"
}
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;
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With