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

来源:这里教程网 时间:2026-02-16 13:03:08 作者:

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

要了解这些程序,您应该熟悉以下C 编程概念:

    C 编程for循环C 编程while循环

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

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

#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;}

输出:

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

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

#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;}

输出:

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

看看这些相关的 C 程序:

    C 程序:查找数组元素之和C 程序:查找商和余数C 程序:交换两个数字C 程序:查找数字的阶乘

相关推荐