I was trying to do some simple exercises on recursive functions:

1. Write a function using Recursion to print numbers from n to 0.

My solution:

int integer(int n)
{
      if(n>=0)
      {
           printf("\n%d",n);
           integer(--n);
       }
}

The next exercise was

2. Write a function using Recursion to print numbers from 0 to n. (You just need to shift one line in the program of problem 1.)

Well i dont know how to do it using recursion; at least not by shifting just one line of the previous code. And also did not want to use any other variables.
Is there any simple solution to the 2nd problem. Help me out?

[b]#include[/b] <stdio.h> 

[b]void[/b] [b]foo[/b]([b]int[/b] n)
{
   [b]if[/b] ( n >= 0 )
   {
	  [b]printf[/b]("%d ", n);
	  [b]foo[/b](n - 1);
   }
}

[b]void bar[/b]([b]int[/b] n)
{
   [b]if[/b] ( n >= 0 )
   {
	  [b]bar[/b](n - 1);
	  [b]printf[/b]("%d ", n);
   }
}

[b]int main[/b]() 
{
   [b]int[/b] value = 5;
   [b]foo[/b](value); [b]putchar[/b]('\n');
   [b]bar[/b](value); [b]putchar[/b]('\n');
   [b]return[/b] 0; 
}

/* my output
5 4 3 2 1 0 
0 1 2 3 4 5 
*/
commented: Thanx, man +11

Man! that was easy!!! Now why did I not think about that? ...MAN! I am a dumbass.

very good.. now i understand recursion a little better now hehe..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.