Decimal to Octal ISC Computer Science 2011 Theory

A class DeciOct has been defined to convert a decimal number into its equivalent octal number. Some of the members of the class are given below:

Class name: DeciOct
Data members/instance variables:
n: stores the decimal number.
oct: stores the octal equivalent number.
Member functions:
DeciOct(): constructor to initialize the data members n = 0, oct = 0.
void getNum(int num): assign num to n.
void deciOct(): calculates the octal equivalent of 'n' and stores it in 'oct' using the recursive technique.
void show(): displays the decimal number 'n', calls the function deciOct() and displays its octal equivalent.
(a) Specify the class, giving details of all the functions, including main() to create an object and call the functions accordingly to enable the task.
(b) State any two disadvantages of using recursion.

import java.util.Scanner;
class DeciOct{
    int n;
    int oct;
    public DeciOct(){
        n = 0;
        oct = 0;
    }
    public void getNum(int num){
        n = num;
    }
    public void deciOct(){
        if(n > 0){
            int d = n % 8;
            n /= 8;
            deciOct();
            oct = oct * 10 + d;
        }
    }
    public void show(){
        System.out.println("Decimal number: " + n);
        deciOct();
        System.out.println("Octal equivalent: " + oct);
    }
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int num = Integer.parseInt(in.nextLine());
        DeciOct obj = new DeciOct();
        obj.getNum(num);
        obj.show();
    }
}

Two disadvantages of recursion:
a) Recursion is dependent on stack which has a limited capacity.
b) More memory is required because each time recursion takes place, new copy of variables gets created.

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