Decimal to Octal Java Program | 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 nn): assign nn to n
void deci_oct(): 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 deci_oct() and displays its octal equivalent.

(a) Specify the class DeciOct, giving details of the constructor(), void getnum(int), void deci_oct() and void show(). Also define a main() function to create an object and call the functions accordingly to enable the task.

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

(b) State any two disadvantages of using recursion.
1. Recursion may lead to stack overflow.
2. Recursion has more overhead when compared to iterative statements.