1 to n and the sum is calculated using a recursive function

This problem required to achieve a 1 + 2 + 3 + ... + n and a simple calculation using recursive functions.

Function interface definition:

int sum (int n);

For this function returns the incoming positive integer n 1 + 2 + 3 + ... + n and; if n is not a positive integer, 0 is returned. Title ensure that the input and output range in a long integer. I recommend trying written recursive functions.

Referee test program Example:

#include <stdio.h>

int sum( int n );

int main()
{
    int n;

    scanf("%d", &n);
    printf ("%d\n", sum(n));

    return 0;
}

/* 你的代码将被嵌在这里 */

Sample Input 1:

10

Output Sample 1:

55

Sample Input 2:

0

Output Sample 2:

0

int sum( int n )
{
	int i,sum=0;
	for(i=1;i<=n;i++)
	{
		sum+=i;
	}
	return sum;
}
Published 45 original articles · won praise 26 · views 227

Guess you like

Origin blog.csdn.net/Noria107/article/details/104212870