# C program for converting decimal to octal base not working for all numbers

Discussion in 'C' started by amitSingh95, Jul 5, 2014.

1. ### amitSingh95New Member

Joined:
Jul 5, 2014
Messages:
3
0
Trophy Points:
0
I am a C beginner and I tried to write a program to convert numbers from decimal base to octal. The program is not working for higher numbers and for those between 192 and 2890(both included). For the numbers in that range, it displays octal value one less than the correct one and for higher numbers, it displays octal value one greater.

Code:
```#include <stdio.h>
#include <math.h>
int main()
{
int quo, rem, inp, oct=0;
printf("Input the number(positive integer only)\n");
scanf("%d", &inp);
quo=inp;
for(int i=0;quo!=0;i++)
{
rem=quo%8;
quo=quo/8;
oct=oct+(pow(10, i)*rem);
}
printf("The octal equivalent of %d is = %d\n", inp, oct);
main();
return 0;
}
```
Please tell me what is wrong with my code.
I am using Codelite.
Thanks.

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
I fed your code into Visual Studio 2010 and apart from having to fix the ambiguity in the call to pow() I made no changes. It ran fine, giving the expected values (all checked with Windows Calc in Programmer mode):
The octal equivalent of 1 is = 1
Input the number(positive integer only)
8
The octal equivalent of 8 is = 10
Input the number(positive integer only)
80
The octal equivalent of 80 is = 120
Input the number(positive integer only)
191
The octal equivalent of 191 is = 277
Input the number(positive integer only)
192
The octal equivalent of 192 is = 300
Input the number(positive integer only)
2890
The octal equivalent of 2890 is = 5512
Input the number(positive integer only)
2891
The octal equivalent of 2891 is = 5513
Input the number(positive integer only)

If you want the program to run indefinitely it's better to enclose it in a for ( ; ; ) loop than to recursively call main at the end. Eventually the program will run out of stack space and you'll get undefined behaviour.

So: what's wrong with your code? Nothing. It's a compiler bug.

Last edited: Jul 6, 2014
3. ### amitSingh95New Member

Joined:
Jul 5, 2014
Messages:
3
0
Trophy Points:
0
Thanks @xpi0t0s
But when I changed the data type of variable oct to float, the program started to work perfectly. Does the bug have anything to do with precision loss?

4. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
Possibly, yes. pow() is a floating point number so if it thinks, for example, that 10^2=99.999999 then that would explain your observations. A better way than using these floating point approximations is to use an integer which stores the current power of 10; start it at 1, and multiply it by 10 on each iteration, then replace pow(10,i) with a reference to that integer.

Joined:
Jul 5, 2014
Messages:
3