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?

Recommended Answers

[code][color=darkgreen][b]#include[/b][/color]

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

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

[b][color=blue]int[/color] [color=red]main[/color][/b]()
{
[b][color=blue]int[/color][/b] value = [color=teal]5[/color];
[b][color=red]foo[/color]/b; …

Jump to Post

All 3 Replies

Re: Recursion 80 80
[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
Re: Recursion 80 80

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

Re: Recursion 80 80

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 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.