C program to convert octal numbers to decimal numbers; Through this tutorial, we will learn how to convert octal numbers to decimal numbers in c programs with the help of functions.
Algorithm to Convert Octal to Decimal
Use the following algorithm to write a program to convert octal numbers to decimal numbers; as follows:
- Take an input octal number from user and stored in an int type variable say octal.
- Create A function, which name convert().
- Digits of octal are extracted one by one starting from right.
int rem = octal%10;
2. Extracted digits are multiplied with proper base i.e. power of 8.
int res = rem*pow(8,i);
3. After multiplying each digit with proper base the results are added and stored in another variable say decimal.
decimal += res;
- Call Convert function with parameters.
- The output is printed.
C Program To Convert Octal to Decimal
#include <stdio.h>
// Function to convert octal number to decimal
int convert(int octal)
{
int decimal = 0, i = 0;
//converting octal to decimal
while (octal != 0)
{
int rem = octal % 10;
octal /= 10;
int res=rem*pow(8,i);
decimal += res;
i++;
}
return decimal;
}
//main program
int main()
{
int octal;
printf("Enter an octal number: ");
//user input
scanf("%d", &octal);
//calling function
int decimal=convert(octal);
//printing output
printf( " %d in octal = %d in decimal", octal, decimal);
return 0;
}
The output of the above c program; as follows:
Enter an octal number: 120255
120255 in octal = 41133 in decimal