Recursive c++

Given an integer n>0, write a recursive C++ function that writes the integers 1,2,...,n.?

 ``1234567891011121314151617181920`` ``````#include using namespace std; int d(int); int main() { int n; cout<<"Enter a whole number: "; cin>>n; for (int i=1;i<=n;i++) { cout<<"The preceeding numbers are: "<
Last edited on
This is fairly simple :

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 :)

 ``1234567891011121314151617`` ``````#include using namespace 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<1 call: function(2-1) //step 3 print<<2<1 //1 is NOT greater than 1 so.. call: function(1-1) //there are not step 4 print<

Console
 ``` Eyenrique-MacBook-Pro:Desktop Eyenrique\$ ./RecNum Enter a number (greater than zero): 3 1 2 3 ```

Code
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950`` ``````//RecNum.cpp //## #include using std::cout; using std::cin; using std::endl; bool numberIsGreaterThanZero(int number); void RecursiveSequence(int number); int main(){ int number; cout<<"Enter a number (greater than zero): "; cin>>number; if(numberIsGreaterThanZero(number)){ RecursiveSequence(number); }else{ cout<<"Is not greater than zero!"<0)return true; return false; }//end function numberIsGreaterThanZero void RecursiveSequence(int number){ if(number>1){ //Recursive statement RecursiveSequence(number-1); cout<
 ``12345678910111213141516171819202122232425`` ``````#include 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) ; }``````
I am not at my computer with my compilier so I can't test this...

However I might try something like this...

 ``123456789101112131415161718192021222324`` ``````#include using namespace std; void print_numbers_to_n(int n, int i) { if(i n; print_numbers_to_n(n, i); return 0; } ``````
Thank you all, especially @zsteve.
I figured it out though.
Topic archived. No new replies allowed.