943,901 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Marked Solved
  • Views: 4094
  • C RSS
Jun 5th, 2004
1

Re: Recursion

Expand Post »
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:

  1. int integer(int n)
  2. {
  3. if(n>=0)
  4. {
  5. printf("\n%d",n);
  6. integer(--n);
  7. }
  8. }

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?
Similar Threads
Reputation Points: 113
Solved Threads: 3
Posting Whiz
Asif_NSU is offline Offline
353 posts
since Apr 2004
Jun 5th, 2004
2

Re: Recursion

#include <stdio.h> 

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

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

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

/* my output
5 4 3 2 1 0 
0 1 2 3 4 5 
*/
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Jun 5th, 2004
0

Re: Recursion

Man! that was easy!!! Now why did I not think about that? ...MAN! I am a dumbass.
Reputation Points: 113
Solved Threads: 3
Posting Whiz
Asif_NSU is offline Offline
353 posts
since Apr 2004
Nov 10th, 2010
0
Re: Recursion
very good.. now i understand recursion a little better now hehe..
Reputation Points: 10
Solved Threads: 0
Newbie Poster
rexel0924 is offline Offline
1 posts
since Nov 2010

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: Sorting Array
Next Thread in C Forum Timeline: Strings that look the same but are not.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC