Recursive Function namely without using loop

Hi Friends,
I have program the below code however I could not programming as recursive function and I want help of you


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
//Example program
#include <iostream>
using namespace std;

int getsayi (int sayi) {

     int niyahet,temp1=0;
    for (int sayac=0; sayac<=sayi; sayac++)
    {
   
    niyahet=temp1+sayac+1;
    temp1=niyahet;
    cout<<niyahet<<" ";
    //cout<<sayac;
        
    }
    

return 1;
}

int main()
{
  int isayi;
  cout << "enter your wanted number: ";
  cin >> isayi;
  getsayi(isayi);
 
}



enter your wanted number: 100
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 
210 231 253 276 300 325 351 378 406 435 465 496 528 561
 595 630 666 703 741 780 820 861 903 946 990 1035 1081 
1128 1176 1225 1275 1326 1378 1431 1485 1540 1596 
1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 
2278 2346 2415 2485 2556 2628 2701 2775 2850 2926
 3003 3081 3160 3240 3321 3403 3486 3570 3655 3741
 3828 3916 4005 4095 4186 4278 4371 4465 4560 4656 
4753 4851 4950 5050 5151 
Last edited on
For comparison:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void recursive(int n, int lim) {
    if ( n < lim ) {
        cout << n << endl;
        recursive(n+1,lim);
    }
}

void iterative(int n) {
    for ( int i = 0 ; i < n ; i++ ) {
        cout << i << endl;
    }
}

int main()
{
    iterative(5);
    recursive(0,5);
}


Recursion is simpler if you can count down to 0, as you don't have to keep passing the end condition around.

Or more generally, recursion is simpler if the problem naturally divides into similar (but smaller) problems. Like n! is expressed in terms of (n-1)! until you reach the trivial 1! and/or 0!.
Topic archived. No new replies allowed.