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