Jump to content

c++ program

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
shehroz ali

shehroz ali

    Newbie

  • Members
  • Pip
  • 1 posts
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.

#2
Namesake

Namesake

    Newbie

  • Members
  • PipPip
  • 21 posts
Sounds like homework.

If you're not allowed to use an if-else statement, consider using while loops

Cprogramming.com Tutorial: Loops

#3
alienkinetics

alienkinetics

    Programmer

  • Members
  • PipPipPipPip
  • 154 posts
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
alienkinetics

alienkinetics

    Programmer

  • Members
  • PipPipPipPip
  • 154 posts
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);

  }

}