Convert decimal to octal number in C, C++, Java and Python | faceprep

Program to convert a number from decimal to octal is discussed here. Given a decimal number as input, which has to be converted to its equivalent octal number.

For example, decimal number 200 has to be converted to octal.

  • 200 / 8 = 25 , rem = 0
  • 25 / 8 = 3 , rem = 1
  • 3 / 8 = 0 , rem = 3

The equivalent octal number of the decimal number 200 is 310.

decimal to octal

Algorithm to convert a number from decimal to octal

  1. Input the decimal number.
  2. Divide the decimal number by 8.
  3. Store the remainder.
  4. Repeat steps 2 and 3 until the number can be divided.
  5. Print the reverse of the remainder, which is the octal equivalent of the decimal number.

Program to convert a number from decimal to octal

// C program to convert a number from decimal to octal

#include <stdio.h>
#include <math.h>

int decimal_to_octal(int decimal);
int main()
{
int decimal;

printf(“\nEnter a decimal number: “);
scanf(“%d”, &decimal);

printf(“\nEquivalent octal number : %d\n”, decimal_to_octal(decimal));

return 0;
}

int decimal_to_octal(int decimal)
{
int octal = 0, i = 1;

while (decimal != 0)
{
octal += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}

return octal;
}

// C++ program to convert a number from decimal to octal

#include <iostream>
#include <math.h>
using namespace std;

int decimal_to_octal(int decimal)
{
int octal = 0, i = 1;

while (decimal != 0)
{
octal += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}

return octal;
}

int main()
{
int decimal;

cout << “\nEnter a decimal number: “;
cin >> decimal;

cout << “\nEquivalent octal number : ” << decimal_to_octal(decimal);
cout << endl;

return 0;
}

// Java program to convert a number from decimal to octal

import java.util.*;
public class Main
{
public static int decimal_to_octal(int decimal)
{
int octal = 0, i = 1;

while (decimal != 0)
{
octal += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}

return octal;
}

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the decimal number : “);
int decimal = sc.nextInt();
System.out.print(“\nEquivalent octal number : ” + decimal_to_octal(decimal));
}
}

# Python program to convert a number from decimal to octal

def decimal_to_octal(decimal):
octal = 0
i = 1
while (decimal != 0):
octal = octal + (decimal % 8) * i
decimal = int(decimal / 8)
i = i * 10;

return octal;

decimal = int(input(“Enter the decimal number : “))
print(“Equivalent octal number : “,decimal_to_octal(decimal))

Output:

decimal to octal

Time complexity: O(n)