KnowledgeBoat Logo

Computer Applications

Write a menu driven class to accept a number from the user and check whether it is a Palindrome or a Perfect number.

(a) Palindrome number: (A number is a Palindrome which when read in reverse order is same as in the right order)

Example: 11, 101, 151 etc.

(b) Perfect number: (A number is called Perfect if it is equal to the sum of its factors other than the number itself.)

Example: 6 = 1 + 2 + 3

Java

Java Iterative Stmts

ICSE 2008

177 Likes

Answer

import java.util.Scanner;

public class KboatPalinOrPerfect
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Palindrome number");
        System.out.println("2. Perfect number");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter number: ");
        int num = in.nextInt();

        switch (choice) {
            case 1:
            int copyNum = num;
            int revNum = 0;

            while(copyNum != 0) {
                int digit = copyNum % 10;
                copyNum /= 10;
                revNum = revNum * 10 + digit;
            }

            if (revNum == num) 
                System.out.println(num + " is palindrome");
            else
                System.out.println(num + " is not palindrome");
            break;

            case 2:
            int sum = 0;

            for (int i = 1; i <= num / 2; i++) {
                if (num % i == 0) {
                    sum += i;
                }
            }

            if (num == sum) 
                System.out.println(num + " is a perfect number");
            else
                System.out.println(num + " is not a perfect number");
            break;

            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a menu driven class to accept a number from the user and check whether it is a Palindrome or a Perfect number. (a) Palindrome number: (A number is a Palindrome which when read in reverse order is same as in the right order) Example: 11, 101, 151 etc. (b) Perfect number: (A number is called Perfect if it is equal to the sum of its factors other than the number itself.) Example: 6 = 1 + 2 + 3BlueJ output of Write a menu driven class to accept a number from the user and check whether it is a Palindrome or a Perfect number. (a) Palindrome number: (A number is a Palindrome which when read in reverse order is same as in the right order) Example: 11, 101, 151 etc. (b) Perfect number: (A number is called Perfect if it is equal to the sum of its factors other than the number itself.) Example: 6 = 1 + 2 + 3

Answered By

59 Likes


Related Questions