Natural number

Natural numbers are numbers that are common and clear in nature. As such, it is a whole, non-negative number.

Logic

To print the sum of first N natural numbers, we need to run one loop from 1 to N, and each time inside the loop we have to add / sum value of “i” (current number) into one temporary variable.

Once the loop is over, outside of the loop we have to print a temporary variable containing the sum of natural numbers.

See also: Print first N natural numbers using for loop

Program

import java.util.Scanner;

public class SumOfNatural {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take number from user
        System.out.print("Enter any number : ");
        int num = scanner.nextInt();

        int sum = 0;

        for(int i = 1; i <= num; i++) {

            sum += i;
        }

        System.out.println("\nSum of first " + num + " natural numbers : " + sum);
    }

}

Output

Enter any number : 50
Sum of first 50 natural numbers = 1275