Convert Decimal To Octal program in C++
Written by
Convert Decimal To Octal program
A decimal number is taken and converted into its octal equivalent.
Example:
Decimal number: 50
Corresponding octal number: 62
Algorithm
- Create a long integer variable called
dno
and prompt the user to enter a decimal number using thecout
andcin
functions. - Initialize a long integer variable called
temp
to the value ofdno
. - Create an array of integers called
octal
with a size of 100 and an integer variable calledi
initialized to 1. - Use a while loop to repeatedly divide
temp
by 8 and store the remainder in theoctal
array at indexi
. Incrementi
and assign the result oftemp
divided by 8 totemp
. The loop should continue untiltemp
becomes 0. - After the loop, use a for loop to iterate over the
octal
array starting at indexj
equal toi - 1
and ending at indexj
greater than 0. Inside the loop, print the value ofoctal[j]
using thecout
function.
Code:
#include <iostream>
using namespace std;
int main() {
long dno, temp;
int octal[100], i = 1, j;
cout << "Enter the decimal number: ";
cin >> dno;
temp = dno;
while (temp != 0) {
octal[i++] = temp % 8;
temp = temp / 8;
}
cout << "Equivalent octal value of decimal no: ";
for (j = i - 1; j > 0; j--) {
cout << octal[j];
}
return 0;
}
Output
Enter the decimal number: 123
Equivalent octal value of decimal no: 173