# C 程序：查找前 n 个自然数的和

> 原文： [https://beginnersbook.com/2017/10/c-program-to-find-the-sum-of-first-n-natural-numbers/](https://beginnersbook.com/2017/10/c-program-to-find-the-sum-of-first-n-natural-numbers/)

程序查找前`n`个自然数的总和。我们将看到计算自然数的总和的两个 C 程序。在第一个 C 程序中，我们使用`for`循环查找总和，在第二个程序中，我们使用`while`循环执行相同操作。

要了解这些程序，您应该熟悉以下 [C 编程](https://beginnersbook.com/2014/01/c-tutorial-for-beginners-with-examples/)概念：

1.  [C 编程`for`循环](https://beginnersbook.com/2014/01/c-for-loop/)
2.  [C 编程`while`循环](https://beginnersbook.com/2014/01/c-while-loop/)

## 示例 1：使用`for`循环查找自然数之和的程序

用户输入`n`的值，程序使用`for`循环计算前`n`个自然数的总和。

```c
#include <stdio.h>
int main()
{
    int n, count, sum = 0;

    printf("Enter the value of n(positive integer): ");
    scanf("%d",&n);

    for(count=1; count <= n; count++)
    {
        sum = sum + count;
    }

    printf("Sum of first %d natural numbers is: %d",n, sum);

    return 0;
}
```

输出：

```c
Enter the value of n(positive integer): 6
Sum of first 6 natural numbers is: 21
```

## 示例 2：使用`while`循环查找自然数的总和

```c
#include <stdio.h>
int main()
{
    int n, count, sum = 0;

    printf("Enter the value of n(positive integer): ");
    scanf("%d",&n);

    /* When you use while loop, you have to initialize the
     * loop counter variable before the loop and increment
     * or decrement it inside the body of loop like we did 
     * for the variable "count"
     */
    count=1;
    while(count <= n){
    	sum = sum + count;
    	count++;
    }

    printf("Sum of first %d natural numbers is: %d",n, sum);

    return 0;
}
```

输出：

```c
Enter the value of n(positive integer): 7
Sum of first 7 natural numbers is: 28
```

看看这些相关的 C 程序：

1.  [C 程序：查找数组元素之和](https://beginnersbook.com/2014/06/c-program-to-find-sum-of-array-elements-using-pointers-recursion-functions/)
2.  [C 程序：相加两个数字](https://beginnersbook.com/2017/09/c-program-to-add-two-numbers/)
3.  [C 程序：查找商和余数](https://beginnersbook.com/2017/09/c-program-to-find-quotient-and-remainder/)
4.  [C 程序：交换两个数字](https://beginnersbook.com/2017/09/c-program-to-swap-two-numbers/)
5.  [C 程序：查找数字的阶乘](https://beginnersbook.com/2014/06/c-program-to-find-factorial-of-number-using-recursion/)