Pages

Custom Search

Monday, October 31, 2011

Program to find Octal of a number [ C++ ].

Problem Statement:
 Design, develop, and execute a program in C++ to create a class
called OCTAL, which has the characteristics of an octal number.
Implement the following operations by writing an appropriate
constructor and an overloaded operator +.
i.) OCTAL h = x ; where x is an integer
ii.) int y = h + k ; where h is an OCTAL object and k is an
integer.
Display the OCTAL result by overloading the operator <<. 
Also display the values of h and y.





Source Code: 


 #include <iostream.h>  
 #include <math.h>  
 class OCTAL  
 {  
     int data;  
     public:  
     OCTAL(int t = 0)               //Constructor  
     {  
         int num, rem, n=0, oct;  
         data = t;  
         num = data;  
         oct = 0;  
         while(num)  
         {  
             rem = num % 8;  
             oct = oct + rem * pow(10, n);  
             num = num / 8;  
             n++;  
         }  
         data = oct;  
     }  
     int operator +(int t)           // Overloaded + operator  
     {  
         int num, rem, n=0, oct;  
         int y = data + t;  
         num = y;  
         oct=0;  
         while(num)  
         {  
             rem = num % 8;  
             oct = oct + rem * pow(10, n);  
             num = num / 8;  
             n++;  
         }  
         y=oct;  
         return (y);  
     }  
     friend ostream & operator <<(ostream & dout, OCTAL h)  // Overloaded <<(insertion) operator  
     {  
         dout<<h.data;  
         return (dout);  
     }  
 };  
 int main()  
 {  
     int x, k, y;  
     cout<<"\nEnter a number to get its octal: ";  
     cin>>x;  
     cout<<"\nEnter value of k: ";  
     cin>>k;  
     OCTAL h = x;  
     cout<<"\nValue of x: "<<x;  
     y = h + k;  
     cout<<"\nOctal of "<<x<<": ";  
     cout<<h;  
     cout<<"\nOctal of y(h+k): "<<y<<endl;   
 }  

SAMPLE OUTPUTS:



No comments:

Custom Search