Recursion

Thread Solved
Reply

Join Date: Apr 2004
Posts: 353
Reputation: Asif_NSU is on a distinguished road 
Solved Threads: 2
Asif_NSU's Avatar
Asif_NSU Asif_NSU is offline Offline
Posting Whiz

Re: Recursion

 
1
  #1
Jun 5th, 2004
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?
"He who mixes with people and endures the harm they do is better than he who does not mix and endures." (Tirmidhi)
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 4,311
Reputation: Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future Dave Sinkula has a brilliant future 
Solved Threads: 228
Team Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: Recursion

 
2
  #2
Jun 5th, 2004
#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 
*/
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
Reply With Quote Quick reply to this message  
Join Date: Apr 2004
Posts: 353
Reputation: Asif_NSU is on a distinguished road 
Solved Threads: 2
Asif_NSU's Avatar
Asif_NSU Asif_NSU is offline Offline
Posting Whiz

Re: Recursion

 
0
  #3
Jun 5th, 2004
Man! that was easy!!! Now why did I not think about that? ...MAN! I am a dumbass.
"He who mixes with people and endures the harm they do is better than he who does not mix and endures." (Tirmidhi)
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC