Write a recursive function to calculate sum of first n natural numbers.
时间: 2024-11-10 17:14:22 浏览: 20
要编写一个递归函数来计算前n个自然数的和,可以参考以下Python代码:
```python
def sum_of_natural_numbers(n):
"""
使用递归计算前n个自然数的和
参数:
n -- 需要计算和的自然数的数量
返回:
和 -- 前n个自然数的总和
"""
if n == 0: # 基线条件:当n为0时,返回0(空和)
return 0
else:
# 递归条件:如果n不为0,则将当前数字n加上前一个数的和
return n + sum_of_natural_numbers(n - 1) # 召唤自身并传入n-1
# 测试函数
n = 5
result = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is: {result}")
```
这个递归函数首先检查基本情况(即n等于0),在这种情况下直接返回0。对于其他的n值,函数会通过递归调用自身,每次减少1,直到达到基础情况为止。在每次递归调用过程中,都会把当前的数字n加到前一个数的和上。
相关问题
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
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`.
阅读全文