The positive integers 1, 2, 3, 4 etc. are known as natural numbers. Here we will see three programs to calculate and display the sum of natural numbers.
- First Program calculates the sum using while loop
- Second Program calculates the sum using for loop
- Third Program takes the value of n(entered by user) and calculates the sum of n natural numbers
To understand these programs you should be familiar with the following concepts of Core Java Tutorial:
Example 1: Program to find the sum of natural numbers using while loop
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);
    }
}
Output:
Sum of first 10 natural numbers is: 55
Example 2: Program to calculate the sum of natural numbers using for loop
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);
    }
}
Output:
Sum of first 10 natural numbers is: 55
Example 3: Program to find sum of first n (entered by user) natural numbers
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);
    }
}
Output:
Enter the value of n: 20 Sum of first 20 natural numbers is: 210
Leave a Reply