C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Product of First N Natural Numbers

import java.util.Scanner;

 

public class ProductOfNaturalNumbers {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

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

        int n = sc.nextInt();

 

        long product = 1;

 

        // Loop to calculate product

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

            product *= i;

        }

 

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

 

        sc.close();

    }

}

Output

 
INPUT :
Enter the value of N: 5

OUTPUT :
Product of first 5 natural numbers is: 120
 

Explanation

1. What Does the Program Do?

It calculates:

1 × 2 × 3 × ... × N

This is called factorial.

2. Logic Used

long product = 1;

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

    product *= i;

}

  • Starts multiplication from 1
  • Multiplies each number up to N
  • Uses long to handle large results

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

1 × 2 = 2

2 × 3 = 6

6 × 4 = 24

24 × 5 = 120

4. Program Flow

  1. Accept value of N
  2. Initialize product = 1
  3. Multiply numbers from 1 to N
  4. Display final result