C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Sum of first N Natural Numbers

import java.util.Scanner;

 

public class SumOfNaturalNumbers {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter the value of N: ");

        int n = sc.nextInt();

 

        int sum = 0;

 

        // Loop to calculate sum

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

            sum += i;

        }

 

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

 

        sc.close();

    }

}

Output

 
INPUT :
Enter the value of N: 10

OUTPUT :
Sum of first 10 natural numbers is: 55
 

Explanation

1. What are Natural Numbers?

Natural numbers are positive integers starting from 1:
1, 2, 3, 4, 5, ...

2. Logic Used

The program uses a for loop:

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

    sum += i;

}

This adds each number from 1 to N to the variable sum.

3. Step-by-Step Example (N = 5)

1 + 2 + 3 + 4 + 5 = 15

4. Program Flow

  1. Read the value of N
  2. Initialize sum to 0
  3. Loop from 1 to N and add values
  4. Display the final sum

Alternative Formula Method

You can also compute directly using:

Sum=n(n+1)/2