Decimal to Octal and Octal to Decimal Conversion in C

In Computer Science, generally Octal number system used to store big data values. We can also convert from Binary to Decimal, Decimal to Binary and Octal to Decimal, Octal to Binary and Binary to Octal also can be done. In this post, we will write the programs for decimal to octal and octal to decimal conversion in C language.

Note:- 8 & 9 are not present in the Octal number system.

For decimal to octal conversion in C, we need to calculate power. So, we will use pow() function defined under standard library function math.h

C program to convert decimal to octal using while loop

`````` #include<stdio.h>
#include<math.h>
int main()
{
int dec, oct=0, rem, i=0;

printf("Enter Decimal Number: ");
scanf("%d",&dec);

while(dec!=0)
{
rem = dec%8;
oct += (rem * pow(10,i));
dec /= 8;
i++;
}

printf("Octal value= %d",oct);

return 0;
}``````

Output:-

Enter Decimal Number: 10
Octal Value= 12

Decimal to Octal conversion in C using Function

A function is a block of code that performs a specific task. For example, the main is a function and every program execution starts from the main function in C programming.

The C program is made of one or more functions. Every program must have at least one function with the name `main`. The execution of the program always starts from the main function and ends with the main function. The main function can call other functions to do some special task.

The function is a small program is used to do a particular task. In C a big program divided into several small subroutines/functions/procedures. Hence C is a function-oriented programming language.

`````` #include<stdio.h>
#include<math.h>
void convert(int n);
int main()
{
int decimal;

printf("Enter Decimal Number: ");
scanf("%d",&decimal);

convert(decimal);

return 0;
}

void convert(int n)
{
int oct=0, rem, i=0;

while(n!=0)
{
rem = n%8;
oct += (rem*pow(10,i));
n /= 8;
i++;
}

printf("Octal Value= %d",oct);
}``````

C program to convert octal to decimal

`````` #include<stdio.h>
#include<math.h>
int main()
{
int oct, dec=0, rem, i=0;

printf("Enter a Octal Number: ");
scanf("%d",&oct);

while(oct!=0)
{
rem = oct%10;
dec += (rem * pow(8,i));
oct /= 10;
i++;
}

printf("Decimal Value = %d",dec);

return 0;
}``````

Output:-

Enter Octal Number: 24
Decimal Value = 20

Convert Octal to Decimal using Function

`````` #include<stdio.h>
#include<math.h>
int convert(int n);
int main()
{
int octal;

printf("Enter a Octal Number: ");
scanf("%d", &octal);

printf("Decimal Value = %d", convert(octal) );

return 0;
}

int convert(int n)
{
int decimal=0, rem, i=0;

while(n != 0)
{
rem = n%10;
decimal += (rem * pow(8,i));
n /= 10;
i++;
}
return decimal;
}``````

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!