programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# recursion

aaron koh
Greenhorn
Posts: 1
H, i am currently learning recursion, and i have a query.

I have a program that receives user input, and outputs the decimal input into binary form.

In my recursive function, i have a if else loop to check if operation is completed. The problem i face is this.

The final return, when input finally hits zero is concatenating 0 to whatever i have this far. e.g. Decimal 10 should give 1010, but because of the "return 0", instead of getting
1010+0, i am getting 10100.
I can solve the problem by creating a variable sum,and passing along, but i am just curious why the final return 0 is giving me not a +0,but a concatenate 0.

Thanks in advance for the help rendered.

Ulf Dittmer
Rancher
Posts: 42972
73
Welcome to JavaRanch.

I don't quite understand what the calculation does, but I would start by converting everything from "int" to "double". Casting double results to int -as the code is currently doing- is bound to result in numerical inaccuracies otherwise. (Of course, using double introduces its own inaccuracies, but for small numbers that should be fine).

Matthew Brown
Bartender
Posts: 4568
9
I don't think the problem is that it's concatenating - integers won't work like that. It might be clearer if you told us what the input was, but I'd be suspicious about that ++weight on line 11. Do you realise that the calculated value you print out on line 10 is not the same as the calculated value added to your result on line 11, because weight is incremented between the calculations? That would make a factor of 10 difference, which is what you're seeing.

My guess is that weight + 1 would do what you need, rather than ++weight.

 It is sorta covered in the JavaRanch Style Guide.