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
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
+ 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.
+ 2
Well i m confused a bit with the second output
+ 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
+ 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;
}
+ 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. :)
+ 1
Thank you so much for your support. :)
+ 1
@sayan
Thank you for the answer :)
0
So,
if(true) is always true???
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...