C Program to Convert Decimal number to Octal Number
Logic of This Program :
In this program we are accepting the decimal number from the user and decimal number is converted into the equivalent octal number with simple steps -
[box]
Steps to Convert Decimal to Octal :
- Accept the given decimal number
- If the number is less than 8 the octal number is the same
- If the num > 7 then Divide the number with 8
- Write down the remainder
- Do steps 3 and 4 with the quotient till that quotient is less than 8
- Write the remainders in reverse order (bottom to top)
- The resultant is the equivalent octal number to the given decimal number
C Program to Convert Decimal number into Octal Number :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include<stdio.h> #include<conio.h> #include<math.h> void dec_oct(long int num) // Function Definition { long int rem[50],i=0,length=0; while(num>0) { rem[i]=num%8; num=num/8; i++; length++; } printf("nOctal number : "); for(i=length-1;i>=0;i--) printf("%ld",rem[i]); } //================================================ void main() { long int num; clrscr(); printf("Enter the decimal number : "); scanf("%ld",&num); dec_oct(num); // Calling function getch(); } |
Output :
1 2 |
Enter the decimal number : 20 Octal number : 24 |
Explanation of C Program :
We are dividing the number by 8 and storing the reminder in the rem[] array.
1 2 3 4 5 6 7 |
while(num>0) { rem[i]=num%8; num=num/8; i++; length++; } |
Original number is then divided by 8 and
1 |
num = num / 8; |
We are repeating the steps until ‘num’ is greater than 0.
1 2 3 4 5 |
while(num>0) { --- Logic of --- the Code } |
Now we are printing the reminders stored in an array in reverse order so that equivalent octal number gets printed.
1 2 |
for(i = length-1 ; i >= 0 ; i--) printf("%ld",rem[i]); |
Download Program :
[box]Download Code [/box]