Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here this produces the desired output:

int tri(int n) {
    if (n < 1) return 1;
    return (n+1) + tri(n-1);
}

You can test it like this:

int main(void){
    for (int i=0; i<10; i++) {
        printf("%d: %d
",i,tri(i));
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...