simple recursion function

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
/*Write a program that calculates triangle number by using a recursive function.
A triangle number is the sum of all whole numbers from 1 to N, in which N is the
number specified. For example, triangle(5)= 5+4+3+2+1.*/
#include <iostream>
using namespace std;

int triangle(int a);

int main ()
{
    int i;
    cout << "Enter a number and press ENTER: ";
    cin >> i;
    cout << endl;
    cout << "triangle(" << i << "):  " << triangle(i) << "\n\n";
    
    system ("PAUSE");
    return 0;
}

 int triangle(int a)
 {
     if (1 <= a)
           return (a + triangle(a-1));
 }


when i key in 5 i get 2686591???
i know the problem obviously lies within the triangle function but idk what's wrong with it -_-
Maybe you meant if(a > 1)?
but it says from 1 to N; wouldnt if (a > 1) make the function stop at 2 ?
Last edited on
At 2 it would return 2 + triangle(2-1). You need to have a second return statement that returns 1 if the if condition was false.
Last edited on
i dont get what youre saying "at 2 it would return 2 + triangle(2-1)?
i changed it to
1
2
3
4
5
6
7
 int triangle(int a)
 {
     if (a >= 1)
         return a + triangle(a-1);
     else
         return 0;
 }

and it work! thx
im guessing that because i didnt tell the function what to do after a>=1 it just kept running the function adding 15 + 15 over and over. (just a hypothesis)
thx for your help
No, because there was no return value for one possible branch, it returned a garbage value that was really high. ;)
Topic archived. No new replies allowed.