icse-promo

Question

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:

Classname: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.
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

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class DeciOct
{
    int n,oct,i=0;
    Scanner sc=new Scanner(System.in);
    public DeciOct()
    {
        n=0;
        oct=0;
        i=0;
    }
    public void getnum(int nn)
    {
        n=nn;
    }
    public void deci_oct()
    {
        int c;
        
        if(n!=0)
        {
            c=n%8;
            n=n/8;
            oct=oct+c*(int)Math.pow(10,i);
            i=i+1;
            deci_oct();
            
            
        }
        
    }
    public void show()
    {
        System.out.println("Decimal number="+n);
        deci_oct();
        System.out.println("Octalequivalent="+oct);
    }
    public static void main()
    {	
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a decimal num:");
        int num=sc.nextInt();
        DeciOct ob1=new DeciOct();
        ob1.getnum(num);
        ob1.show();
    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *