About robin

I am a Computer Science Teacher from India. Blogging is my hobby.

Mighty Numbers | ISC Computer Science 2025 Improvement Exam Paper

A class Mighty has been defined to create m1 and m2 as mighty numbers from integers n1 and n2. m1 will become mighty by placing the eventual sum of digits of n2 at the end of n1. m2 will become mighty by placing the eventual sum of digits of n1 at the end of n2.

Example:
If n1 = 235, the eventual sum of digits of n1 = 1
n2 = 106, the eventual sum of digits of n2 = 7
then, m1 = 2357
m2 = 1061

The details of the members of the class are given below:
Class name: Mighty
Data members/instance variables:
n1: to store first integer
n2: to store second integer
m1: to store the first mighty number
m2: to store the second mighty number
Methods/Member functions:
Mighty(): constructor to initialize data members with legal initial values
void accept(): to accept values for n1 and n2
int sumOfDigits(int x): to return the eventual sum of digits of x using recursive technique
void calMighty(): to calculate mighty numbers m1 and m2 by invoking sumOfDigits()
void display(): to display mighty numbers m1 and m2

Specify the class Mighty giving details of the constructor, void accept(), int sumOfDigits(int), void calMighty() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class Mighty{
    int n1;
    int n2;
    int m1;
    int m2;
    public Mighty(){
        n1 = 0;
        n2 = 0;
        m1 = 0;
        m2 = 0;
    }
    public void accept(){
        Scanner in = new Scanner(System.in);
        System.out.print("First integer: ");
        n1 = in.nextInt();
        System.out.print("Second integer: ");
        n2 = in.nextInt();
    }
    public int sumOfDigits(int x){
        if(x < 10)
            return x;
        int sum = 0;
        while(x > 0){
            sum += x % 10;
            x /= 10;
        }
        x = sum;
        return sumOfDigits(x);
    }
    public void calMighty(){

        String s1 = n1 + "" + sumOfDigits(n2);
        String s2 = n2 + "" + sumOfDigits(n1);
        m1 = Integer.parseInt(s1);
        m2 = Integer.parseInt(s2);
    }
    public void display(){
        System.out.println("m1 = " + m1);
        System.out.println("m2 = " + m2);
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        Mighty obj = new Mighty();
        obj.accept();
        obj.calMighty();
        obj.display();
    }
}