C Program to Convert Octal Number to Decimal

In this example, you will learn to convert octal to decimal numbers. Here we write a C program that takes an octal number as input and converts it into an equivalent decimal number. Converting an octal number to decimal means converting the number with base value 10 to base value 8.

The base value of a number system determines the number of digits used to represent a numeric value. For example, a decimal number system uses 10 digits 0-9 to represent any numeric value.

 

Given an octal number n, you need to convert to a decimal number.

Examples:

Input : n = 30
Output : 24
24 is decimal equivalent of octal 30.


Input : n = 11
Output : 9

 

 

Logic to Convert Octal Number to Decimal:

Step-1: Arrange the octal number with the power of 8 and start from the right-hand side. For example,

1278 => 1 × 82 + 2 × 81 + 7 × 80

Step-2: Evaluate the power of 8 values for each octal number and multiply it with the respective numbers.

1278 => 1 × 64 + 2 × 8 + 7 × 1 

1278 => 64 + 16 + 7

 

Step-3: Now in the last add all values to get the respective decimal number.

1278 => 8710

 

C Program to Convert Octal Number to Decimal

 

Method 1: Using math.h library function

 

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

int OctalToDecimal(int octNum)
{
    int decNum = 0, i = 0;

    while(octNum != 0)
    {
        decNum += (octNum%10) * pow(8,i);
        ++i;
        octNum/=10;
    }

    return decNum;
}

int main()
{
    int octNum;

    printf("Enter an octal number: ");
    scanf("%d", &octNum);

    //Function Call to convert octal to decimal
    const int decNum = OctalToDecimal(octNum);

    printf("%d = %d in decimal\n", octNum, decNum);

    return 0;
}

Output:

C Program to Convert Octal Number to Decimal Aticleworld

 

 

Method 2:

Extract the digits of a given octal number, beginning with the rightmost digit, and store them in a variable called last_digit. Now multiply the last_digit by the appropriate base value (Power of 8) and add the result to the variable decNum. Repeat the process till the given octal number becomes zero.

#include <stdio.h>

int octalToDecimal(int octNum)
{
    int decNum = 0;

    // Initializing baseValue value to 1, i.e 8^0
    int baseValue = 1;

    int temp = octNum;
    while (temp)
    {
        // Extracting last digit
        int last_digit = temp % 10;

        // Multiplying last digit with appropriate
        // base value and adding it to decNum
        decNum += last_digit * baseValue;

        baseValue = baseValue * 8;

        temp = temp / 10;
    }

    return decNum;
}


int main()
{
    int octNum;

    printf("Enter an octal number: ");
    scanf("%d", &octNum);

    //Function Call to convert octal to decimal
    const int decNum = octalToDecimal(octNum);

    printf("%d = %d in decimal", octNum, decNum);

    return 0;
}

 

Recommended Post:

Leave a Reply

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