Q&A ICSE2015-09A #7375
Question:
Use 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 number itself.)
Example :
Sample Input : n = 15.
Sample 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 :
Sample Input : n = 5
Sample Output : 120.
For an incorrect choice, an appropriate error message should be displayed.
Answer:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("1. Factors");
System.out.println("2. Factorial");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter n: ");
int n = scanner.nextInt();
for (int i = 1; i < n; i++) {
if (n % i == 0) {
System.out.println(i);
}
}
break;
case 2:
System.out.print("Enter n: ");
n = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial = factorial * i;
}
System.out.println("Factorial: " + factorial);
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
