C Program to convert a decimal number to an octal number

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

Expected Output:

1st run:

2nd run:

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:

12510 =  1758

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:

50010 =  7648

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

 

 

Leave a Comment

%d bloggers like this: