Here is a C program to convert a decimal number to octal number. Decimal number system is a base 10 number system using digits for 0 to 9 whereas octal number system is base 8 and using digits from 0 to 7. Given a decimal number as input from user we have to print the octal equivalent of input decimal number.
For Example:
100 in Decimal is equivalent to 144 in Octal number system.
- Divide the input decimal number by 8 and store the remainder.
- Store the quotient back to the input number variable.
- Repeat this process till quotient becomes zero.
- Equivalent octal number will be the remainders in above process in reverse order.
Suppose input decimal number is 525
Step 1. 525/8 , Remainder = 5, Quotient = 65
Step 2. 65/8 , Remainder = 1, Quotient = 8
Step 3. 8/8 , Remainder = 0, Quotient = 1
Step 4. 1/8 , Remainder = 1, Quotient = 0
Now, the Octal equivalent of 525 is the remainders in reverse order : 1015
C program to convert a decimal number to octal number
#include <stdio.h> long decimalToOctal(long n); int main() { long decimal; printf("Enter a decimal number\n"); scanf("%ld", &decimal); printf("Octal number of %ld is %ld", decimal, decimalToOctal(decimal)); return 0; } long decimalToOctal(long n) { int remainder; long octal = 0, i = 1; while(n != 0) { remainder = n%8; n = n/8; octal = octal + (remainder*i); i = i*10; } return octal; }Output
Enter a decimal number 1234 Octal number of 1234 is 2322
C program to convert a octal number to decimal number
#include <stdio.h> #include <math.h> long octalToDecimal(long n); int main() { long octal; printf("Enter an octal number\n"); scanf("%ld", &octal); printf("Decimal number of %ld(Octal) is %ld", octal, octalToDecimal(octal)); return 0; } long octalToDecimal(long n) { int remainder; long decimal = 0, i=0; while(n != 0) { remainder = n%10; n = n/10; decimal = decimal + (remainder*pow(8,i)); ++i; } return decimal; }Output
Enter an octal number 45132 Decimal number of 45132(Octal) is 19034
Related Topics