🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 程序:查找自然数之和 > 原文: [https://beginnersbook.com/2017/09/java-program-to-find-sum-of-natural-numbers/](https://beginnersbook.com/2017/09/java-program-to-find-sum-of-natural-numbers/) 正整数`1,2,3,4`等被称为自然数。在这里,我们将看到三个程序来计算和显示自然数的总和。 * 第一个程序使用`while`循环计算总和 * 第二个程序使用`for`循环计算总和 * 第三个程序取`n`的值(由用户输入)并计算`n`个自然数的总和 要了解这些程序,您应该熟悉[核心 Java 教程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)的以下概念: * [Java `For`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/) * [Java `While`循环](https://beginnersbook.com/2015/03/while-loop-in-java-with-examples/) ## 示例 1:使用`while`循环查找自然数之和的程序 ```java public class Demo { public static void main(String[] args) { int num = 10, count = 1, total = 0; while(count <= num) { total = total + count; count++; } System.out.println("Sum of first 10 natural numbers is: "+total); } } ``` **输出:** ```java Sum of first 10 natural numbers is: 55 ``` ## 示例 2:使用`for`循环计算自然数之和的程序 ```java 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); } } ``` 输出: ```java Sum of first 10 natural numbers is: 55 ``` ## 示例 3:用于查找前`n`个(由用户输入)自然数之和的程序 ```java 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); } } ``` **输出:** ```java Enter the value of n: 20 Sum of first 20 natural numbers is: 210 ```