C++ Program to Convert Decimal to Octal

«
»

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

Problem Description

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

Problem Solution

1. A decimal number is entered.
2. The number is divided by 8 and the remainders are stored.
3. The result is printed in reverse order.
4. Exit.

C++ Program/Source code

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

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.     long num, temp;
  6.     int oct[50], i = 1, j;
  7.     cout << "Enter a decimal number : ";
  8.     cin >> num;
  9.     temp = num;
  10.     while (temp != 0)
  11.     {
  12.         oct[i++] = temp % 8;
  13.         temp = temp / 8;
  14.     }
  15.     cout << "\nOctal equivalent of " << num << " is : ";
  16.     for (j = i-1; j >= 0; j--)
  17.         cout << oct[j];
  18.     return 0;
  19. }
Program Explanation

1. The user is asked to enter a decimal number.
2. Its value is stored in the long variable ‘num’ and copied in a temporary variable ‘temp’.
3. Using a while loop, the remainders of temp are calculated, dividing it by 8.
4. The remainders are stored in the array ‘oct’.
5. The loop terminates when quotient becomes 0.
6. The array oct is then printed in reverse order which is the octal equivalent of the number entered.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter a decimal number : 8
Octal equivalent of 8 is : 10
 
Case 2 :
Enter a decimal number : 33
Octal equivalent of 33 is : 41
 
Case 3 :
Enter a decimal number : 441
Octal equivalent of 441 is : 671

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

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

Participate in C++ Programming Certification Contest of the Month Now!

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.