Octal to decimal conversion in c

C code to convert octal number to decimal number

#include<stdio.h>
#include<math.h>

int main(){

long int octal,decimal =0;
int i=0;

printf("Enter any octal number: ");
scanf("%ld",&octal);

while(octal!=0){
decimal = decimal + (octal % 10) * pow(8,i++);
octal = octal/10;
}

printf("Equivalent decimal value: %ld",decimal);

return 0;
}

Sample output:

Enter any octal number: 346
Equivalent decimal value: 230

C program to change octal to decimal

#include<stdio.h>

int main(){

long int octalNumber;

printf("Enter any octal number: ");
scanf("%o",&octalNumber);

printf("Equivalent decimal number is: %d",octalNumber);

return 0;
}

Sample output:

Enter any octal number: 17
Equivalent decimal number is: 15

Algorithm:

Octal to decimal conversion method:

To convert an octal number to decimal number multiply each digits separately of octal number from right side by  8^0,8^1,8^2,8^3 … respectively and then find out the sum of them.

Octal to decimal conversion examples:

For example we want to convert octal number 3401 to decimal number.

Step 1: 1 * 8 ^0 = 1*1 =1
Step 2: 0 * 8 ^1 = 0*8 =0
Step 3: 4 * 8 ^2 = 4*64 =256
Step 4: 3 * 8 ^3 = 3*512 =1536

Sum= 1 + 0 + 256 + 1536 = 1793

So, (3401)8 = (1793)10

6. Write a c program to convert octal number to hexadecimal number.
8. Write a c program to convert hexadecimal number to octal number.
9. Write a c program to convert hexadecimal number to decimal number.
10. Write a c program to convert binary number to octal number.

1 comment: Anonymous said...

Your code do not seem to work.