Categories
Class 11 Class 12

Decimal to Octal ISC 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.

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

State any two disadvantages of using recursion.

import java.io.*;
class DeciOct{
    private int n;
    private int oct;
    public DeciOct(){
        n = 0;
        oct = 0;
    }
    public void getNum(int num){
        n = num;
    }
    public void deciOct(){
        if(n > 0){
            int rem = n % 8;
            n /= 8;
            deciOct();
            oct = oct * 10 + rem;
        }
    }
    public void show(){
        System.out.println("Decimal number: " + n);
        deciOct();
        System.out.println("Octal equivalent: " + oct);
    }
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int num = Integer.parseInt(br.readLine());
        DeciOct obj = new DeciOct();
        obj.getNum(num);
        obj.show();
    }
}

Two disadvantages of using recursion:

  • Each time, the function calls itself, fresh memory is allocated.
  • Recursion is comparatively slower than the iterative method.

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.