We need to write a C program to convert an octal number to a decimal number.
Example:
1 2 3 4 5 |
Input: 14 Output: 12 Input: 5 Output: 5 |
Convert Octal to Decimal in C using Loop
An Octal number can be converted to its corresponding decimal form by summing the multiplication of each of its digits to its respective value of 8 to the power of its index (i.e position from the right – 1). Same as depicted in the above picture.
For this, we have to use a loop in which we will extract each of its digits one by one and multiply them with its respective 8x value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> #include <stdlib.h> int main() { int oct, i=0, decimal = 0, lastDigit; printf("Enter a Octal number \n"); scanf("%d",&oct); while(oct != 0){ lastDigit = oct%10; //remainder is the last digit //Add by multiplying the last digit with the 8x decimal = decimal + pow(8,i) * lastDigit; oct = oct/10; //update octal by removing the last digit i = i+1; //power (exponent) } printf("Decimal: %d", decimal); return 0; } |
Output
Convert Octal to Decimal in C using Recursion
The approach used in this method is the same as the above program but is implemented using recursion.
On each recursive call, we need to pass the octal number by eliminating its last digit. The recursive call will stop when there is only single left in the octal (i.e base condition).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <stdio.h> #include <stdlib.h> //'i' represents the nth recursive call as well as //nth digit from left, so it can be used as an exponent int octToDec(int oct, int i){ if(oct >= 0 && oct <= 7) return pow(8,i)*oct; int lastDigit = oct%10; return (pow(8,i) * lastDigit) + octToDec(oct/10, ++i); } int main() { int oct, decimal; printf("Enter a Octal number \n"); scanf("%d",&oct); decimal = octToDec(oct,0); printf("Decimal: %d", decimal); return 0; } |
Output
Comment below your suggestions or doubts.