C Program to Convert Decimal to Octal Number
Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int decimal, i = 0, octal[20]; printf("Enter a decimal number: "); scanf("%d", &decimal); if (decimal == 0) { printf("Octal: 0\n"); return 0; } int num = decimal; while (num > 0) { octal[i++] = num % 8; num /= 8; } printf("Octal: "); for (int j = i - 1; j >= 0; j--) { printf("%d", octal[j]); } printf("\n"); return 0; }
Dry Run
Let's trace the decimal number 10 through the code to convert it to octal.
Input
decimal = 10
Initialize
i = 0, num = 10
First division
num % 8 = 10 % 8 = 2; octal[0] = 2; num = 10 / 8 = 1; i = 1
Second division
num % 8 = 1 % 8 = 1; octal[1] = 1; num = 1 / 8 = 0; i = 2
Print octal
Print octal[1] then octal[0]: 1 2
| Iteration | num | Remainder (num % 8) | octal array | i |
|---|---|---|---|---|
| 1 | 10 | 2 | [2] | 1 |
| 2 | 1 | 1 | [2, 1] | 2 |
Why This Works
Step 1: Divide by 8 to find octal digits
Each division by 8 gives a remainder that is one octal digit, because octal is base 8.
Step 2: Store remainders in order
We store remainders in an array as we get them, which represent digits from least significant to most.
Step 3: Print digits in reverse
Since the first remainder is the last digit, we print the array backwards to get the correct octal number.
Alternative Approaches
#include <stdio.h> void decToOctal(int n) { if (n == 0) return; decToOctal(n / 8); printf("%d", n % 8); } int main() { int decimal; printf("Enter a decimal number: "); scanf("%d", &decimal); if (decimal == 0) printf("0\n"); else decToOctal(decimal); printf("\n"); return 0; }
#include <stdio.h> int main() { int decimal; printf("Enter a decimal number: "); scanf("%d", &decimal); printf("Octal: %o\n", decimal); return 0; }
Complexity: O(log n) time, O(log n) space
Time Complexity
The loop divides the number by 8 each time, so it runs about log base 8 of n times, which is O(log n).
Space Complexity
We store each remainder in an array, so space grows with the number of octal digits, also O(log n).
Which Approach is Fastest?
Using printf with %o is fastest and simplest, recursion uses call stack, and manual array method is educational but uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual division and array | O(log n) | O(log n) | Learning and understanding conversion |
| Recursion | O(log n) | O(log n) (call stack) | Elegant code, less storage management |
| printf %o format specifier | O(1) | O(1) | Quick and practical conversion |