icse-promo

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.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class program9
{
	public static void main(String[] args)
	{
	    int i=0,n=0,factorial=0;
		Scanner sc = new Scanner(System.in);
		System.out.println("press 1 for Factors");
		System.out.println("press 2 for Factorial");
		System.out.print("Enter your choice: ");
		int choice = sc.nextInt();
		switch (choice)
		{
			case 1:
				System.out.print("Enter a number: ");
				n = sc.nextInt();
				for (i = 1; i < n; i++)
				{
					if (n % i == 0)
					{
						System.out.println(i);
					}
				}
				break;
			
			case 2:
				System.out.print("Enter a number: ");
				n = sc.nextInt();
				factorial = 1;
				for (i = 1; i <= n; i++)
				{
					factorial = factorial * i;
				}
				System.out.println("Factorial: " + factorial);
				break;
			
			default:
				System.out.println("Invalid choice");
				break;
		}
	}
}

				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *