Print the output as follows by a c program without using loops?

Print the output as follows by a c program without using loops?
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1

Showing Answers 1 - 6 of 6 Answers

This can easily be done with 3 recursive functions.

The first function will print out a sequence from 1 to n:

void printSeq1(int n)
{
if (n > 1)
printSeq1(n - 1);
printf("%d ", n);
}

The second function will print N sequences from 1, 1 2, 1 2 3, etc.:

void printSeq2(int n)
{
if (n > 1)
printSeq2(n - 1);
printSeq1(n);
}

The third function will print N sequence from 1 2 3, 1 2, etc.

void printSeq3(int n)
{
printSeq1(n);
if (n > 1)
printSeq3(n - 1);
}

Put it all together in one function:

void printSeq(int n)
{
printSeq2(n - 1);
printSeq1(n);
printSeq3(n - 1);
}

int main(void)
{
printSeq(4);
return 0;
}

Voila.

  Was this answer useful?  Yes

Sai Praveen Gampa

  • Nov 1st, 2011
 

No need of three functions.
Good thought to use Recursive.
I have just divided that output as..
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1

Dont mind if you want the same output as you specified just remove
printf("
");
Line from the code.

Code
  1. #include<stdio.h>

  2. static int temp1=1,temp2=1,n=4;

  3. int max=0;

  4. main()

  5. {

  6.  if(temp1<=temp2)

  7.  {

  8.   printf("%d ",temp1);

  9.   temp1++;

  10.   main();

  11.  }

  12.  else

  13.  {

  14.   printf("

  15. ");

  16.   if(temp2==n)

  17.         max=1;

  18.   if(max==1)

  19.   {

  20.         if(temp2>0)

  21.         {

  22.                 temp2--;

  23.                 temp1=1;

  24.                 main();

  25.         }

  26.   }

  27.   else

  28.   {

  29.         temp2++;

  30.         temp1=1;

  31.         main();

  32.   }

  33.  }

  34. }

  35.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions