Home / Programs / Using the switch statement, write a menu driven program: To check and display whether a number input by the user is a composite number or not.A number is said to be composite, if it has one or more than one factors excluding 1 and the number itself.Example: 4, 6, 8, 9... To find the smallest digit of an integer that is input:Sample input: 6524Sample output: Smallest digit is 2 For an incorrect choice, an appropriate error message should be displayed.
Programming Example

Using the switch statement, write a menu driven program:

  1. To check and display whether a number input by the user is a composite number or not.
    A number is said to be composite, if it has one or more than one factors excluding 1 and the number itself.
    Example: 4, 6, 8, 9...
  2. To find the smallest digit of an integer that is input:
    Sample input: 6524
    Sample output: Smallest digit is 2

For an incorrect choice, an appropriate error message should be displayed.

👁 220 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Program Code

import java.util.Scanner;

public class RAnsariNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for Composite Number");
        System.out.println("Type 2 for Smallest Digit");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();

        switch (ch) {
            case 1:
            System.out.print("Enter Number: ");
            int n = in.nextInt();
            int c = 0;
            for (int i = 1; i <= n; i++) {
                if (n % i == 0)
                    c++;
            }

            if (c > 2)
                System.out.println("Composite Number");
            else
                System.out.println("Not a Composite Number");
            break;

            case 2:
            System.out.print("Enter Number: ");
            int num = in.nextInt();
            int s = 10;
            while (num != 0) {
                int d = num % 10;
                if (d < s)
                    s = d;
                num /= 10;
            }
            System.out.println("Smallest digit is " + s);
            break;

            default:
            System.out.println("Wrong choice");
        }
    }
}

Output

Type 1 for Composite Number
Type 2 for Smallest Digit
Enter your choice: 1
Enter Number: 9
Composite Number
Press any key to continue . . .


Type 1 for Composite Number
Type 2 for Smallest Digit
Enter your choice: 2
Enter Number: 6524
Smallest digit is 2
Press any key to continue . . .

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.