Magic Number ISC Computer Science 2009 Theory

magic number is a number in which the eventual sum of digits of the number is equal to 1.

For example, 172.
1 + 7 + 2 = 10.
1 + 0 = 1.
Then, 172 is a magic number.
Design a class Magic to check if a given number is a magic number. Some of the members of the class are given below:
Class name: Magic
Data members/instance variables:
n: stores the number.
Member functions:
Magic(): constructor to assign 0 to n.
void getNum(int num): to assign the parameter value to the number, n = num.
int sumOfDigits(int num): returns the sum of the digits of a number.
void isMagic(): checks if the given number is a magic number by calling the function sumOfDigits(int) and displays an appropriate message.

import java.util.Scanner;
class Magic{
    int n;
    public Magic(){
        n = 0;
    }
    public void getNum(int num){
        n = num;
    }
    public int sumOfDigits(int num){
        if(num < 10)
            return num;
        return num % 10 + sumOfDigits(num / 10);
    }
    public void isMagic(){
        int result = n;
        do{
            result = sumOfDigits(result);
        }while(result > 9);
        if(result == 1)
            System.out.println("Magic number!");
        else
            System.out.println("Not a Magic number.");
    }
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = Integer.parseInt(in.nextLine());
        Magic obj = new Magic();
        obj.getNum(num);
        obj.isMagic();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory