Write a program in C to calculate the sum of numbers from 1 to n using recursion. Input: Input a positve integer n. Output : Compute the summation of 1+2+...+n. Sample of Input: 5 Sample of Output: 15
时间: 2024-02-24 07:58:26 浏览: 112
Sure, I can help you with that. Here's the C program to calculate the sum of numbers from 1 to n using recursion:
```c
#include <stdio.h>
int sum(int n);
int main() {
int n, result;
printf("Enter a positive integer: ");
scanf("%d", &n);
result = sum(n);
printf("The sum of numbers from 1 to %d is %d.\n", n, result);
return 0;
}
int sum(int n) {
if (n == 0) {
return 0;
} else {
return n + sum(n-1);
}
}
```
Explanation:
The program takes a positive integer `n` as input from the user and calls the `sum()` function with `n` as argument.
The `sum()` function is a recursive function that takes an integer `n` as input and returns the sum of numbers from 1 to `n`.
If `n` is 0, the function returns 0. Otherwise, it adds `n` to the sum of numbers from 1 to `n-1` by calling itself recursively with `n-1` as argument.
Finally, the program outputs the result, which is the sum of numbers from 1 to `n`.
阅读全文