HomeC ProgrammingC program to Convert Decimal to Octal Number

C program to Convert Decimal to Octal Number

This C program converts a decimal number to its equivalent octal representation.

Problem statement

You need to convert a decimal number to its octal representation.

C program to Convert Decimal to Octal

#include <stdio.h>

int decimalToOctal(int decimalNumber) {
    int octalNumber = 0, i = 1;

    while (decimalNumber != 0) {
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;

    return octalNumber;

int main() {
    int decimalNumber;

    printf("Decimal to Octal Converter\n");
    printf("Enter a decimal number: ");
    scanf("%d", &decimalNumber);

    int octalNumber = decimalToOctal(decimalNumber);

    printf("Octal number: %d\n", octalNumber);

    return 0;

How it works?

  1. The program defines a function decimalToOctal() that takes a decimal number as input and returns the equivalent octal number.
  2. Inside the decimalToOctal() function, we initialize the octalNumber variable to 0 and i variable to 1. These variables will be used to calculate the octal number.
  3. We use a while loop that continues until the decimal number becomes 0.
  4. Inside the loop, we update the octalNumber by adding the remainder of decimalNumber divided by 8 multiplied by i. This is done to convert the remainder to the corresponding octal digit at the appropriate place value.
  5. We then divide decimalNumber by 8 to move on to the next digit.
  6. We multiply i by 10 to update the place value for the next digit.
  7. Finally, we return the octalNumber.
  8. In the main() function, we prompt the user to enter a decimal number and store it in the decimalNumber variable using scanf().
  9. We call the decimalToOctal() function with decimalNumber as an argument and store the returned octal number in the octalNumber variable.
  10. Finally, we display the converted octal number using printf().


C program to Convert Decimal to Octal


Leave A Reply

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

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...