### Select Articles

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

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.

Algorithm to convert a number from decimal to octal

Input the decimal number.

Divide the decimal number by 8.

Store the remainder.

Repeat steps 2 and 3 until the number can be divided.

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

#include

#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++

#include

#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>

cout << endl>

return 0;

}

JAVA

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 3

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

Input- Enter a decimal number:200 Output- Equivalent octal number :310

Time complexity: O(n)