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().

Input/Output

C program to Convert Decimal to Octal

Share:

Leave A Reply

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

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...