Sum of n numbers read from the input.
Program:
#include<stdio.h>
int read_sum(int); /* function prototype */
int main()
{
int n;
printf("enter number of numbers");
scanf("%d",&n); /* read number of numbers */
printf("%d",read_sum(n)); /* print sum */
return 0;
}
int read_sum(int n) /* function definition */
{
if(n==0) /* base case i.e., if n=0 stop recursion and return 0 */
return 0;
int x; /* if n is not zero read and evaluate sum */
scanf("%d",&x);
return x+read_sum(n-1); /* recursive function call */
}
Sample input:
5
1 2 3 4 5
Output:
15
No comments:
Post a Comment