This example uses "tail recursion", that is, the recursive step occurring before the processing (except for the exiting condition). Tail recursion is useful for doing things "backwards", i.e. this example, when you have 'n' and you want to go from 1 to n.
("forwards" here would be going from n to 1).
Hope that helped :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int rec_print(int n){
if(n==1) return 0;
rec_print(n-1);
cout << n << endl;
return 0;
}
int main(){
int n;
cout << "n?" << endl << '>' ;
cin >> n;
rec_print(n);
}
Hi @mickey4691,
i do not know if
this is the best
solution but it works;
Pseudo code
number entered: 3
function(3) //step 1
if 3 > 1
call: function(3-1) //step 2
print<<3<<space; //this is waiting until step 2 finish
else //never happens
print<<number<<space;
//step2
function(2)
if 2>1
call: function(2-1) //step 3
print<<2<<space; //this is waiting until step 3 finish
else //never happens
print<<number<<space;
//step 3
function(1)
if 1>1 //1 is NOT greater than 1 so..
call: function(1-1) //there are not step 4
print<<number<<space; //never happens
else //print number 1
print<<1<<space; //this is the first output
//followed by the rest that are waiting: 2,3
Console
Eyenrique-MacBook-Pro:Desktop Eyenrique$ ./RecNum
Enter a number (greater than zero): 3
1 2 3
#include <iostream>
void print_all_numbers_from_1_up_to( int n )
{
if( n > 0 ) // if n is less than one, there is nothing to be printed
{
// we need to: print all numbers starting from from 1 up to n
// how do we do that?
// simple: first print all numbers starting from from 1 up to (n-1)
print_all_numbers_from_1_up_to( n-1 ) ;
// and finally, print the number n
std::cout << n << '\n' ;
}
}
int main()
{
int n ;
std::cout << "number? " ;
std::cin >> n ;
print_all_numbers_from_1_up_to(n) ;
}