C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu Driven - Factors/Factorial Program - Java Programs

Using the switch statement, write a menu-driven program to:
(i) To find and display all the factors of a number input by the user (including 1 and excluding the number itself).
Example:
INPUT:
n = 15
OUTPUT:
1, 3, 5
(ii) To find and display the factorial of a number input by the user. The factorial of a non-negative integer n, denoted by n!, is the product of all integers less than or equal to n.

Example:
INPUT:
n = 5
OUTPUT:
5! = 1 × 2 × 3 × 4 × 5 = 120.
For an incorrect choice, an appropriate error message should be displayed.

import java.util.Scanner; class Menu{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("1. Display factors"); System.out.println("2. Display factorial"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(in.nextLine()); switch(choice){ case 1: System.out.print("N = "); int n = Integer.parseInt(in.nextLine()); for(int i = 1; i <= n; i++){ if(n % i == 0) System.out.println(i); } break; case 2: long f = 1L; System.out.print("N = "); n = Integer.parseInt(in.nextLine()); for(int i = 1; i <= n; i++){ f *= i; } System.out.println("Factorial: " + f); break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
1. Display factors
2. Display factorial
Enter your choice: 1
N = 15
1
3
5
15
 
 OUTPUT 2: 
1. Display factors
2. Display factorial
Enter your choice: 2
N = 5
Factorial: 120