C Program to Convert Octal to Decimal Number
% 10, multiply by powers of 8, and sum them; for example, use a loop with decimal += digit * base and base *= 8.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int octal, decimal = 0, base = 1, digit; printf("Enter an octal number: "); scanf("%d", &octal); while (octal > 0) { digit = octal % 10; decimal += digit * base; base *= 8; octal /= 10; } printf("Decimal number: %d\n", decimal); return 0; }
Dry Run
Let's trace the octal number 17 through the code
Initial values
octal = 17, decimal = 0, base = 1
First iteration
digit = 17 % 10 = 7; decimal = 0 + 7*1 = 7; base = 1*8 = 8; octal = 17 / 10 = 1
Second iteration
digit = 1 % 10 = 1; decimal = 7 + 1*8 = 15; base = 8*8 = 64; octal = 1 / 10 = 0
End loop
octal is 0, loop ends; decimal = 15
| octal | digit | decimal | base |
|---|---|---|---|
| 17 | 7 | 7 | 8 |
| 1 | 1 | 15 | 64 |
Why This Works
Step 1: Extract digits
We use octal % 10 to get the last digit of the octal number because octal digits are base 10 digits representing base 8 values.
Step 2: Calculate decimal value
Each digit is multiplied by base, which starts at 1 and increases by powers of 8, reflecting the place value in octal.
Step 3: Update for next digit
We divide the octal number by 10 to remove the last digit and multiply base by 8 to move to the next higher place value.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char octal[20]; int decimal = 0, base = 1, length, i; printf("Enter an octal number: "); scanf("%s", octal); length = strlen(octal); for (i = length - 1; i >= 0; i--) { int digit = octal[i] - '0'; decimal += digit * base; base *= 8; } printf("Decimal number: %d\n", decimal); return 0; }
#include <stdio.h> #include <stdlib.h> int main() { char octal[20]; printf("Enter an octal number: "); scanf("%s", octal); int decimal = (int)strtol(octal, NULL, 8); printf("Decimal number: %d\n", decimal); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program processes each digit of the octal number once, so the time grows linearly with the number of digits.
Space Complexity
Only a few integer variables are used, so space usage is constant regardless of input size.
Which Approach is Fastest?
Using strtol is fastest and simplest for string input, while manual digit extraction is good for integer input but limited by integer size.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual digit extraction (integer input) | O(n) | O(1) | Simple integer inputs without leading zeros |
| String processing with loop | O(n) | O(1) | Handling large octal numbers and leading zeros |
| Using strtol function | O(n) | O(1) | Fastest and simplest for string inputs |