原文: https://beginnersbook.com/2017/09/java-program-to-find-sum-of-natural-numbers/

正整数1,2,3,4等被称为自然数。在这里,我们将看到三个程序来计算和显示自然数的总和。

  • 第一个程序使用while循环计算总和
  • 第二个程序使用for循环计算总和
  • 第三个程序取n的值(由用户输入)并计算n个自然数的总和

要了解这些程序,您应该熟悉核心 Java 教程的以下概念:

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

  1. public class Demo {
  2. public static void main(String[] args) {
  3. int num = 10, count = 1, total = 0;
  4. while(count <= num)
  5. {
  6. total = total + count;
  7. count++;
  8. }
  9. System.out.println("Sum of first 10 natural numbers is: "+total);
  10. }
  11. }

输出:

Sum of first 10 natural numbers is: 55

示例 2:使用for循环计算自然数之和的程序

public class Demo {

    public static void main(String[] args) {

       int num = 10, count, total = 0;

       for(count = 1; count <= num; count++){
           total = total + count;
       }

       System.out.println("Sum of first 10 natural numbers is: "+total);
    }
}

输出:

Sum of first 10 natural numbers is: 55

示例 3:用于查找前n个(由用户输入)自然数之和的程序

import java.util.Scanner;
public class Demo {

    public static void main(String[] args) {

        int num, count, total = 0;

        System.out.println("Enter the value of n:");
        //Scanner is used for reading user input
        Scanner scan = new Scanner(System.in);
        //nextInt() method reads integer entered by user
        num = scan.nextInt();
        //closing scanner after use
        scan.close();
        for(count = 1; count <= num; count++){
            total = total + count;
        }

        System.out.println("Sum of first "+num+" natural numbers is: "+total);
    }
}

输出:

Enter the value of n:
20
Sum of first 20 natural numbers is: 210