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

Example:

Input:   14
Output:  12

Input:   5
Output:  5

Method 1: Using While Loop

Octal to Decimal

We can convert an octal number to its corresponding decimal form by multiplying each of its digits to its respective exponential value of 8 (i.e. 8position_from_the_right – 1) and adding the respective results.

In our program, we implement it using a while loop. Inside the loop, we extract the digits, multiply them with their respective value of 8x, and add them together to get the decimal representation of the input octal number.

#include <stdio.h>
 
int main()
{
    int oct, i=0, decimal = 0, digit;
 
    printf("Enter an Octal number: \n");
    scanf("%d",&oct);
 
    while(oct != 0){
        //extract the digit
        digit = oct%10;
 
        //multiply the digit with the 8x and add to decimal
        decimal = decimal + pow(8,i) * digit;
 
        //update octal by removing the last digit
        oct = oct/10; 
        
        //increment the exponential power
        i = i+1;
    }
 
    printf("Decimal: %d", decimal);
 
    return 0;
}

Output:

Enter an Octal number:
14
Decimal: 12


Method 2: Using Recursion

We can also convert an octal number to its decimal correspondent using recursion.

#include <stdio.h>
 
//recursive function
int octToDec(int oct, int i){
    /*
        *'i' represents the nth recursive call as well as
        *nth digit from right, so it can be used as an exponent
    */
    
    //base condition - all numbers from of 0 to 7
    if(oct >= 0 && oct <= 7)
        return pow(8,i)*oct;
        
    //extract digit
    int digit = oct%10;
    
    //multiply with 8x and add with the result of next recursive call
    return (pow(8,i) * digit) + octToDec(oct/10, ++i);
}
 
int main()
{
    int oct, decimal;
 
    printf("Enter an Octal number: \n");
    scanf("%d",&oct);
    
    //call the recursive function
    decimal = octToDec(oct,0);
    
    printf("Decimal: %d", decimal);
 
    return 0;
}

Output:

Enter an Octal number:
56
Decimal: 46


The approach used in this method is the same as the above program but is implemented using recursion.

In the function, we extract the digit (last digit) using the modulus operator, multiply it with its respective value of 8i and add it to the next recursive result.

On every recursive call, we pass the octal number after eliminating the last digit.

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

Leave a Reply