Google News
logo
C Program to Convert Octal Number to Decimal Number
* We have created a user defined function for octal to decimal conversion.

* In the following example of C program that converts an octal number to a decimal number :
Program :
#include <stdio.h>
#include <math.h>

int main() {
    int octal, decimal = 0, power = 0;
    printf("Enter an octal number: ");
    scanf("%d", &octal);

    while (octal != 0) {
        int digit = octal % 10;
        decimal += digit * pow(8, power);
        octal /= 10;
        power++;
    }

    printf("The decimal equivalent is %d\n", decimal);
    return 0;
}
Output :
Enter an octal number: 243
The decimal equivalent is 163
Explanation :

* We start by declaring three variables: octal to store the octal number, decimal to store the decimal equivalent, and power to keep track of the current power of 8.

* We ask the user to enter an octal number using printf and scanf.

* We use a while loop to convert each digit of the octal number to decimal. The loop continues until the octal number becomes 0.

* Inside the loop, we get the rightmost digit of the octal number using the modulo operator %, and then multiply it with 8 raised to the current power of 8 using the pow function from the math library. We add this value to the decimal variable.

* We then divide the octal number by 10 to remove the rightmost digit, and increment the power variable by 1 to move to the next digit.

* After the loop, we print the decimal variable as the decimal equivalent using printf.

Note : This program assumes that the input octal number is valid (i.e., it only contains digits from 0 to 7). If the input is invalid, the program may produce unexpected results.