Saturday, July 3, 2021

Decimal To Octal Conversion Using Recursive Function


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.*;
class DeciOct
{
    int n;
    String oct;
    DeciOct()
    {
        n=0;
        oct="";
    }
    private void getnum(int nn)
    {
        n=nn;
    }
    void deci_oct(int a)
    {
        String s="";
        int d=a/8;
        int r=a%8;
        if(r==0)
        return;
        oct=r+oct;
        deci_oct(d);
    }
    void show()
    {
        System.out.println("The Original Number :"+n);
        deci_oct(n);
        System.out.println("Its Octal Equivalent :"+oct);
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the Number :");
        int num=sc.nextInt();
        DeciOct ob=new DeciOct();
        ob.getnum(num);
        ob.show();
    }
}

Other Programs On Numbers: CLICK HERE

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner