Summary: In this programming example, we will learn to convert a decimal number into an Octal number using loop and recursion in C.
Example:
1 2 3 4 5 | Input: 7 Output: 7 Input: 8 Output: 10 |
Method 1: Using While Loop

We can convert a decimal number to its octal representation, by dividing the decimal number by 8 and stacking the sequence of remainders in the bottom-up manner as shown in the above diagram.
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> int main() { int num, octal=0, rem, i=1; printf("Enter a Decimal number: \n"); scanf("%d",&num); //loop until number reduces to 0 while(num != 0) { //get remainder rem = num%8; //stack in bottom-up manner octal = (rem*i) + octal; //update the quotient num = num/8; //update i i= i*10; } printf("Octal: %d", octal); return 0; } |
Output:
Enter a Decimal number:11
Octal: 13
In our program, we concatenate the remainders to the left of the octal
to stack remainders in a bottom-up manner.
We are multiplying the remainder by 10s so then when it is added to the previous remainders (i.e. octal
), it comes to its left.
Method 2: Using Recursion
We can also convert a decimal number into an octal representation by using recursion.
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> //recursive function void decToOct(int n){ if(n > 0){ //recusive call - pass quotient as argument decToOct(n/8); //print remainder printf("%d",n%8); } } int main() { int num; printf("Enter a Decimal number: \n"); scanf("%d",&num); printf("Octal: "); decToOct(num); return 0; } |
Output:
Enter a Decimal number:9
Octal: 11
The approach used here is similar to the previous method, but instead of stacking the remainders, we’re directly outputting it in a bottom-up manner.
In this program, we have used head recursion. We are recursively calling the function before printing the remainder, so the remainder begins to print from the last recursive call, therefore getting output in bottom up manner.
These are the two ways using which we can convert any decimal number to its octal correspondent in the C programming language.