/*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>
usingnamespace 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 -_-
int triangle(int a)
{
if (a >= 1)
return a + triangle(a-1);
elsereturn 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