C++ Program to Convert Octal to Decimal

«
»

This is a C++ Program to Convert a Given Octal Number to its Decimal Equivalent.

Problem Description

The program takes an octal number and converts it into its decimal equivalent.

Problem Solution

1. The program takes an octal number.
2. Using a while loop, each digit is converted to its decimal equivalent by multiplying with powers of 8.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Convert a Given Octal Number to its Decimal Equivalent. The program output is shown below.

  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4. int main()
  5. {
  6.     int num, temp, rem, oct = 0, i = 0;
  7.     cout << "Enter an octal number : ";
  8.     cin >> num;
  9.     temp = num;
  10.     while(temp != 0)
  11.     {
  12.         rem = temp % 10;
  13.         oct += rem * pow(8, i++);
  14.         temp = temp / 10;
  15.     }
  16.     cout << "\nDecimal equivalent of " << num << " is : " << oct;
  17.     return 0;
  18. }
Program Explanation

1. The user is asked to enter an octal number and it is stored in the variable ‘num’.
2. num is copied to a temporary variable ‘temp’. The variables ‘oct’ and ‘i’ are initialized as 0.
3. Using a while loop, the remainder of temp on dividing by 10 is stored in ‘rem’.
4. rem is multiplied with powers of 8 using the function pow() and is added to oct. i is incremented in the function.
5. temp is divided by 10.
6. The loop continues till temp is not equal to 0.
7. The result is then printed.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter an octal number : 135
Decimal equivalent of 135 is : 93
 
Case 2 : 
Enter an octal number : 7                                                                                                      
Decimal equivalent of 7 is : 7
 
Case 3 :
Enter an octal number : 25
Decimal equivalent of 25 is : 21

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.