I'm having trouble with writing recursive functions.
The triangular numbers are as follows:
1 = 1
3 = 1 + 2
6 = 1 + 2 + 3
10 = 1 + 2 + 3 + 4
15 = 1 + 2 + 3 + 4 + 5
21 = 1 + 2 + 3 + 4 + 5 + 6
etc.
The series begins with 1 (the first triangular number). To calculate the nth triangular number, n is added to the previous triangular number. For example, the fourth triangular number is calculated by adding 4 to the third triangular number (which is 6), i.e. 10 = (1 + 2 + 3) + 4.
So far, this is what I've come up with:
int triNum(n)
{
if (n<=1)
return n;
int num = 0;
for (int i = 0; i < n; i++)
{
num = n + triNum(n-1)
}
return num;
}
However I'm not sure that this is the correct answer, can anyone help guide me how I should approach this problem?
See Question&Answers more detail:os