Page 196 - CA_Blue( J )_Class10
P. 196
n = sc.nextInt();
i = n;
while(i > 0) {
s+= i % 10;
i /= 10;
}
if(n % s == 0)
System.out.println(n + " is Niven.");
else
System.out.println(n + " is not Niven.");
}
}
27. 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. [2015]
Ans. import java.util.*;
class switchcase {
public static void main() {
Scanner sc= new Scanner(System.in);
int ch,i,n,f=1;
System.out.println("1. Factors");
System.out.println("2. Factorial");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
switch(ch) {
case 1:
System.out.print("Enter Number: ");
n = sc.nextInt();
System.out.print("Factors of : "+n);
for(i = 1; i < n; i++) {
if(n % i == 0)
System.out.print(i + "\t");
}
break;
case 2:
System.out.print("Enter Number: ");
n = sc.nextInt();
for(i = 1; i <= n; i++)
f =f * i;
System.out.println("Factorial of "+n+" : "+f);
break;
default:
System.out.println("Wrong Choice");
}
}
}
194194 Touchpad Computer Applications-X

