C Program To Convert Decimal To Octal

In this post, we will learn how to convert decimal to octal using C Programming language.

C Program To Convert Decimal To Octal

This program takes a decimal number as an input and converts it into an octal number using a user defined function.

So, without further ado, let’s begin this tutorial.

C Program To Convert Decimal To Octal

// C Program To Convert Decimal To Octal
#include <stdio.h>
#include <math.h>

int decimaltoOctal(int num){
    int octal = 0, temp = 1;
    
    while (num != 0){
        octal = octal + (num % 8) * temp;
        num = num / 8;
        temp = temp * 10;
    }
    return octal;
}

int main(){
    int num;
    
    // Asking for Input
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    
    printf("Equivalent Octal Number is: %d", decimaltoOctal(num));
    return 0;
}

Output

Enter a decimal number: 568
Equivalent Octal Number is: 1070

How Does This Program Work ?

    int num;

In this program, we have declared an int data type variable named as num.

    // Asking for Input
    printf("Enter a decimal number: ");
    scanf("%d", &num);

Then, the user is asked to enter a number. The value of this number will get stored in the num named variable.

    printf("Equivalent Octal Number is: %d", decimaltoOctal(num));

Now, we call the custom function named decimaltoOctal which returns the octal number. 

int decimaltoOctal(int num){
    int octal = 0, temp = 1;
    
    while (num != 0){
        octal = octal + (num % 8) * temp;
        num = num / 8;
        temp = temp * 10;
    }
    return octal;
}

We have defined a custom function named decimaltoOctal which converts and returns decimal numbers into octal numbers.

Conclusion

I hope after going through this post, you understand how to convert decimal to octal using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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