C Program to Convert Octal to Decimal

Write a C Program to Convert Octal to Decimal.

Example,

Input: 245
Output: 165

Input: 472
Output: 314

If the input Octal Number is a char array, then we first convert char array to integer form.

In this article, we are taking the input Octal Number as integer.

How to Convert from Octal to Decimal

Suppose you have a Octal Number,

\bf Octal\;Number = a_n * a_{n-1}*  \ldots* a_{2}* a_{1}* a_{0}\; of\; n  \; digits

The corresponding decimal number is given by

\bf\\*Decimal\; Number = a_n *8^{n} + a_{n-1} *8^{n-1} +  \ldots +a_2 *8^{2}+a_1 *8^{1}+a_0 *8^{0}

Algorithm

Steps

Let octal be the input Octal Number

  1. Initialize p = 0, decimal = 0.
  2. Repeat the following steps while octal > 0.
    • Set r = octal % 10.
    • octal = octal / 10.
    • decimal = decimal + r * 8p
    • p = p + 1.
  3. Return decimal.

Program to Convert Octal to Decimal in C

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

int OctalToDecimal(int n) {
	int p = 0, decimal = 0, r;
	
	while(n>0){
		
		// retrieving the right-most digit of n
		r = n % 10;
		
		// dividing n by 10 to remove the
		// right-most digits since it is already
		// scanned in previous step
		n = n / 10;
		
		decimal = decimal + r * pow( 8 , p );	
		++p;
		
	}
	
	return decimal;
}

int main() {

	int n, i, k;
	printf("Enter Octal: ");
	scanf("%d", &n);
	printf("\nDecimal of Octal Number %d is : %d", n, OctalToDecimal(n));
	return 0;

}

Output

Octal to Decimal Program

What to study next?

  1. Hexadecimal to Decimal

References

https://en.wikipedia.org/wiki/Octal

Leave a Comment

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