Convert Decimal to Octal in C [Loop & Recursion]

programming

Summary: In this programming example, we will learn to convert a decimal number into its Octal representation using loop and recursion in C.

Example:

Input:    7
Output:   7

Input:    8
Output:   10

Method 1: Using While Loop

Decimal to Octal

We can easily convert a decimal number to its octal form, by dividing the number by 8 and stacking the sequence of remainders in the bottom-up manner as shown in the above diagram.

#include <stdio.h>
 
int main()
{
    int num, octal=0, rem, i=1;
 
    printf("Enter a Decimal number: \n");
    scanf("%d",&num);
 
    //loop until number reduces to 0
    while(num != 0)
    {   
        //get remainder
        rem = num%8;
        
        //stack in bottom-up manner
        octal = (rem*i) + octal; 
        
        //update the quotient
        num = num/8;
        
        //update i
        i= i*10;                         
    }
 
    printf("Octal: %d", octal);
 
    return 0;
}

Output:

Enter a Decimal number:
11
Octal: 13


In this program, we are concatenating the remainders to the left of the octal, so that the remainders are stacked in a bottom-up manner.

Also before concatenating, we are multiplying the remainder with 10s. This is because when it is added to the previous remainders (i.e. octal), it will be concatenated to its left.

Method 2: Using Recursion

We can also convert a decimal number into an octal representation by using recursion.

#include <stdio.h>
 
//recursive function
void decToOct(int n){
    if(n > 0){
        //recusive call - pass quotient as argument
        decToOct(n/8);
        
        //print remainder
        printf("%d",n%8);
    }
}
 
int main()
{
    int num;
 
    printf("Enter a Decimal number: \n");
    scanf("%d",&num);
 
    printf("Octal: ");
    decToOct(num);
 
    return 0;
}

Output:

Enter a Decimal number:
9
Octal: 11


The approach used here is similar to the previous method, but instead of stacking the remainders, we’re directly outputting it in a bottom-up manner.

In this program, we have used head recursion. We are recursively calling the function before printing the remainder, so the remainder begins to print from the last recursive call, therefore getting output in bottom up manner.

These are the two ways using which we can convert any decimal number to its octal correspondent in the C programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *