Confused with the outputs. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Confused with the outputs.

Below are the screenshots of two questions from Java challenge. https://drive.google.com/file/d/0B-YZWXC5_VTxN1MtWEZ3TTlTYXc/view?usp=drivesdk https://drive.google.com/file/d/0B-YZWXC5_VTxMFo3bnY5MXBGX2s/view?usp=drivesdk I am not able to get the logic behind the answers.(well I'm not excellent in java). Any help would be much appreciated :) :) thank you

5th Aug 2017, 8:41 AM
Rupak Chowdhury
Rupak Chowdhury - avatar
10 Answers
+ 11
int x = 64; for (//not important) { ++x; if (true) break; x = x+4; } // The above will cause x to only increment once to become 65, because if(true) will always be executed, so the loop breaks. public static int f(int x) { if (x == 0) return 2; else return 1 + f(x - 1); } // in main System.out.println(f(3)); // recursion: 1 + f(3 - 1) 1 + 1 + f(2 - 1) 1 + 1 + 1 + f(1 - 1) 1 + 1 + 1 + 2 5
5th Aug 2017, 8:50 AM
Hatsy Rei
Hatsy Rei - avatar
+ 11
@Rupak That is for the last run, it returns 2. For previous runs, it has returned a number of 1s and the function itself. So you have to add those 1s and the last 2. I think I have illustrated the flow pretty clearly there.
5th Aug 2017, 9:03 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Well i m confused a bit with the second output
5th Aug 2017, 1:07 PM
Saumya
Saumya - avatar
+ 1
for the first pic the output is 65 bcoz the control enters the loop for first time and then incremented ++x then it checked the if condition, which is true. the break statement ends the loop in its first iteration. so you get the value 65
5th Aug 2017, 8:45 AM
Devbrath
Devbrath - avatar
+ 1
if(true) will take the control inside the if statement. if(false) then the control does not go inside the if statement. Syntax if(condition){ statement; } else { statement; }
5th Aug 2017, 8:48 AM
Devbrath
Devbrath - avatar
+ 1
@Hatsy In the last iteration, x==0 and , if(x==0) return 2; so isn't the answer 2? coz at the last iteration x becoming 0 and return 2 as the final output?? bit confused in this recursive function. :)
5th Aug 2017, 9:00 AM
Rupak Chowdhury
Rupak Chowdhury - avatar
+ 1
Thank you so much for your support. :)
5th Aug 2017, 9:29 AM
Rupak Chowdhury
Rupak Chowdhury - avatar
+ 1
@sayan Thank you for the answer :)
5th Aug 2017, 1:19 PM
Rupak Chowdhury
Rupak Chowdhury - avatar
0
So, if(true) is always true???
5th Aug 2017, 8:47 AM
Rupak Chowdhury
Rupak Chowdhury - avatar
0
@RUPAK## true is a boolean operator.. true-false like high-low like 1-0 like right- wrong if( true) is equivalent to (random example) if (3==3) or if(1+1==2) or if(not false) so this statements will always be executed...
5th Aug 2017, 9:55 AM
sayan chandra
sayan chandra - avatar