Magic Print (With Constraints)
Write a program which for any given positive n, print integers from 1 to n and then print
from n-1 to 1 using only a single loop without any explicit if-else statement and not using
any other memory location except loop variable.
Input / Output
Enter a Positive Integer less than 10: 7
Magic Print for n=7: 1 2 3 4 5 6 7 6 5 4 3 2 1
you can take only one variable in the loop.
c++ program
Started by shehroz ali, Feb 10 2010 02:09 AM
3 replies to this topic
#1
Posted 10 February 2010 - 02:09 AM
|
|
|
#2
Posted 10 February 2010 - 03:10 AM
Sounds like homework.
If you're not allowed to use an if-else statement, consider using while loops
Cprogramming.com Tutorial: Loops
If you're not allowed to use an if-else statement, consider using while loops
Cprogramming.com Tutorial: Loops
#3
Posted 10 February 2010 - 04:07 AM
Here are 2 solutions.
void MagicPrint1(int n)
{
int i;
for (i = -n + 1; i < n; i++) printf("%d ", n - abs(i));
}
void MagicPrint2(int n)
{
int i = -n;
while (++i < n) printf("%d ", n - abs(i));
}
#4
Posted 10 February 2010 - 04:34 AM
Here are 2 more. The first only uses one external function, and the second doesn't use a loop at all.
void MagicPrint1(int n)
{
int i;
for (i = 1; i < n << 1; i++) printf("%d ", i - (i / n * (i - n) << 1));
}
int MagicPrint2(int n, int i)
{
printf("%d ", i);
if (i < n)
{
MagicPrint2(n, i + 1);
printf("%d ", i);
}
}


Sign In
Create Account

Back to top









