Sum Problem

Sum Problem

In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + … + n.

Input
he input will consist of a series of integers n, one integer per line.

Output
For each case, output SUM(n) in one line. You can assume the result will be in the range of 32-bit signed integer. Process to the end of file.

Sample Input

 1
 100

ample Output

 1
 5050

運用遞歸

int main(void)
{
    long sum(long);
    long n;
    while(scanf("%ld", &n) == 1)
    {
        printf("%ld\n", sum(n));
    }
}
long sum(long m)
{
    if(m == 1)
    {
        return 1;
    }
    else
    {
        return m + sum(m - 1);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章