Convert Decimal To Octal program in C++

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

  1. Create a long integer variable called dno and prompt the user to enter a decimal number using the cout and cin functions.
  2. Initialize a long integer variable called temp to the value of dno.
  3. Create an array of integers called octal with a size of 100 and an integer variable called i initialized to 1.
  4. Use a while loop to repeatedly divide temp by 8 and store the remainder in the octal array at index i. Increment i and assign the result of temp divided by 8 to temp. The loop should continue until temp becomes 0.
  5. After the loop, use a for loop to iterate over the octal array starting at index j equal to i - 1 and ending at index j greater than 0. Inside the loop, print the value of octal[j] using the cout 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

Convert Decimal To Octal program in C++