Java Tutorial
This java program is used to compute the product of first n numbers using for loop.
Gets the limit value as user input and calculates the product value till limit value and prints the product value.
import java.util.Scanner; class ProductTest { public static void main(String[] values) { int product = 1, limit; Scanner sc = new Scanner(System.in); System.out.println("Calculates Product of first n numbers"); System.out.println("-------------------------------------"); System.out.print("Enter limit number:"); limit = sc.nextInt(); for(int i=1;i<=limit;i++) { product *= i; } System.out.println("Product of first '"+limit+"' numbers: " + product); } }Output:
D:\Java_Programs>javac ProductTest.java D:\Java_Programs>java ProductTest Calculates Product of first n numbers ------------------------------------- Enter limit number:10 Product of first '10' numbers: 3628800
This java program is used to compute the product of first n numbers using while loop.
import java.util.Scanner; class ProductTest { public static void main(String[] values) { int product = 1, limit; Scanner sc = new Scanner(System.in); System.out.println("Calculates Product of first n numbers"); System.out.println("-------------------------------------"); System.out.print("Enter limit number:"); limit = sc.nextInt(); int i=1; while(i<=limit) { product *= i; i++; } System.out.println("Product of first '"+limit+"' numbers: " + product); } }Output:
D:\Java_Programs>javac ProductTest.java D:\Java_Programs>java ProductTest Calculates Product of first n numbers ------------------------------------- Enter limit number:8 Product of first '8' numbers: 40320
This java program is used to compute the product of first n numbers using do while loop.
import java.util.Scanner; class ProductTest { public static void main(String[] values) { int product = 1, limit; Scanner sc = new Scanner(System.in); System.out.println("Calculates Product of first n numbers"); System.out.println("-------------------------------------"); System.out.print("Enter limit number:"); limit = sc.nextInt(); int i=1; do { product *= i; i++; }while(i<=limit); System.out.println("Product of first '"+limit+"' numbers: " + product); } }
D:\Java_Programs>javac ProductTest.java D:\Java_Programs>java ProductTest Calculates Product of first n numbers ------------------------------------- Enter limit number:9 Product of first '9' numbers: 362880
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page