Java 实例 查找自然数之和

来源:这里教程网 时间:2026-02-17 20:16:52 作者:

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

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

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

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

输出:

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:20Sum of first 20 natural numbers is: 210

相关推荐