954,184 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursion

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?

Asif_NSU
Posting Whiz
353 posts since Apr 2004
Reputation Points: 113
Solved Threads: 3
 
<strong>#include</strong> <stdio.h> 

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

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

<strong>int main</strong>() 
{
   <strong>int</strong> value = 5;
   <strong>foo</strong>(value); <strong>putchar</strong>('\n');
   <strong>bar</strong>(value); <strong>putchar</strong>('\n');
   <strong>return</strong> 0; 
}

/* my output
5 4 3 2 1 0 
0 1 2 3 4 5 
*/
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

Asif_NSU
Posting Whiz
353 posts since Apr 2004
Reputation Points: 113
Solved Threads: 3
 

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

rexel0924
Newbie Poster
1 post since Nov 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You