Skip to content

Latest commit

 

History

History
84 lines (61 loc) · 2.58 KB

File metadata and controls

84 lines (61 loc) · 2.58 KB

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

原文: https://beginnersbook.com/2017/10/c-program-to-find-the-sum-of-first-n-natural-numbers/

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

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

  1. C 编程for循环
  2. 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): 6
Sum 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): 7
Sum of first 7 natural numbers is: 28

看看这些相关的 C 程序:

  1. C 程序:查找数组元素之和
  2. C 程序:相加两个数字
  3. C 程序:查找商和余数
  4. C 程序:交换两个数字
  5. C 程序:查找数字的阶乘