OverIQ.com

C Program to convert a decimal number to an octal number

Last updated on September 24, 2020


The following is a C program to convert a decimal number to an octal number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*******************************************************
 Program to convert a decimal number to an octal number
 ******************************************************/

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

int main(void)
{   
    long long num, oct = 0;    
    int i = 0, rem;

    printf("Enter a decimal number: ");
    scanf("%lld", &num);      

    while(num != 0)
    {
        rem = num % 8;  // get the last digit
        oct = rem * (long long)pow(10, i++) + oct;  
        num /= 8;  // get the quotient
    }

    printf("0o");

    printf("%lld", oct);        

    return 0; // return 0 to operating system
}

Try it now

Expected Output: 1st run:

1
2
Enter a decimal number: 74
0o112

2nd run:

1
2
Enter a decimal number: 2545
0o4761

How it works #

To convert a decimal number to an octal number, we follow these steps:

Step 1: Divide the decimal number continuously by 8 and write the remainder on the right-hand side of the dividend. We repeat this process until we get the quotient 0.

Step 2: Write the remainders from bottom to top.

Let's take some examples:

Example 1: Convert decimal 125 to an octal number:

Step 1:

Quotient Remainder
125/8 15 5
15/8 1 7
1/2 0 1

Step 2:

\(\mathtt{125_{10} = 175_{8}}\)

Example 2: Convert decimal 500 to an octal number:

Step 1:

Quotient Remainder
500/8 62 4
62/8 7 6
1/2 0 7

Step 2:

\(\mathtt{500_{10} = 764_{8}}\)

The following table shows what happens at each iteration of the loop (assuming num = 74):

Iteration rem bin num i
After 1st iteration rem=74%8=2 oct=2*(10^0)+0=2 num=74/8=9 i=2
After 2nd iteration rem=9%8=1 oct=1*(10^1)+2=12 num=9/8=1 i=3
After 3rd iteration rem=1%8=1 oct=1*(10^2)+12=112 num=1/8=0 i=4

Recommended Reading