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?
- The program defines a function
decimalToOctal()that takes a decimal number as input and returns the equivalent octal number. - Inside the
decimalToOctal()function, we initialize theoctalNumbervariable to 0 andivariable to 1. These variables will be used to calculate the octal number. - We use a while loop that continues until the decimal number becomes 0.
- Inside the loop, we update the
octalNumberby adding the remainder ofdecimalNumberdivided by 8 multiplied byi. This is done to convert the remainder to the corresponding octal digit at the appropriate place value. - We then divide
decimalNumberby 8 to move on to the next digit. - We multiply
iby 10 to update the place value for the next digit. - Finally, we return the
octalNumber. - In the
main()function, we prompt the user to enter a decimal number and store it in thedecimalNumbervariable usingscanf(). - We call the
decimalToOctal()function withdecimalNumberas an argument and store the returned octal number in theoctalNumbervariable. - Finally, we display the converted octal number using
printf().
Input/Output
