In this java program, you will learn how to calculate the sum of natural numbers. We are using a for
loop and a while
loop for calculating the sum of natural numbers in Java.
The positive numbers 1, 2, 3... are known as natural numbers. Natural numbers are also called counting numbers because they do not include zero(0) or negative numbers. They are a part of real numbers including just the positive integers, but not zero, fractions, decimals, and negative numbers. And their sum is the result of all numbers starting from 1 to the given number.
For n, the sum of natural numbers is:
1 + 2 + 3 + ... + n
// Java Program to Calculate the Sum of Natural Numbers Using For Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int n, sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = scanner.nextInt();
scanner.close();
for (int i = 1; i <= n; ++i) {
// sum = sum + i;
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Enter a Number: 10
Sum = 55
// Java Program to Calculate the Sum of Natural Numbers Using while Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int n, i = 1, sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Number: ");
n = scanner.nextInt();
scanner.close();
while (i <= n) {
sum += i;
i++;
}
System.out.println("Sum = " + sum);
}
}
Enter a Number: 100
Sum = 5050
Comments