Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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;
}
}
}
C. Sir| Created: 16-Apr-2019 | Updated: 16-Apr-2019|ICSE2015