KnowledgeBoat Logo

Computer Applications

Write a menu driven program to display all prime and non-prime numbers from 1 to 100.

Enter 1: to display all prime numbers
Enter 2: to display all non-prime numbers

Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

Java

Java Nested for Loops

49 Likes

Answer

import java.util.Scanner;

public class KboatMenuPrime
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1: to display all prime numbers");
        System.out.println("Enter 2: to display all non-prime numbers");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();

        switch (choice) {
            case 1:
            for (int i = 2; i <= 100; i++) {
                boolean isPrime = true;
                for (int j = 2; j <= i / 2; j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime) 
                    System.out.println(i);
            }
            break;
            
            case 2:
            System.out.println(1);
            for (int i = 2; i <= 100; i++) {
                boolean isPrime = true;
                for (int j = 2; j <= i / 2; j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                if (!isPrime) 
                    System.out.println(i);
            }
            break;
            
            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a menu driven program to display all prime and non-prime numbers from 1 to 100. Enter 1: to display all prime numbers Enter 2: to display all non-prime numbers Hint: A number is said to be prime if it is only divisible by 1 and the number itself.BlueJ output of Write a menu driven program to display all prime and non-prime numbers from 1 to 100. Enter 1: to display all prime numbers Enter 2: to display all non-prime numbers Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

Answered By

15 Likes


Related Questions