+ 6

Can anyone tell me why is the output of this code is 13579 😵

I was challenging someone in Java .. and I got this question //what is the output of this code? boolean b=true ; for (int i = 0 ; i <10 ; i++) if (b = !b) System.out.print (i) ; the Answer was 13579 .. I see that it took only the odd numbers .. But why! 🤔 I really tried to understand it on my own.. but I don't get it. anyway.. thanks for helping ✌️😁

31st Jan 2018, 2:47 AM
Ali Hassan
Ali Hassan - avatar
8 Antworten
+ 23
false 0 //b= !true ... ie false true 1 //b=!false ... ie true false 2 //false true 3 //true . . it goes in alternate order //loop goes from 0 to 9 .... 1 3 5 7 9
31st Jan 2018, 2:59 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 3
Saeed Boss When you write b=!true... In every iteration b=false Hence the condition if(b=!true), becomes false Therefore, no output is displayed... I hope it helps!
31st Jul 2018, 3:44 PM
Nashat
Nashat - avatar
+ 2
Thats tricky because you thought b=!b is checking for similarity.
18th Feb 2019, 8:17 AM
Piyush Yadav
Piyush Yadav - avatar
+ 1
boolean b=true ; for (int i = 0 ; i <10 ; i++) if (b=!b) System.out.print (i); In the beginning "b=true" for i=0--->b=false--->no output for i=1--->b=true--->output =1 for i=2--->b=false--->no output for i=3--->b=true--->output =3 . . . In every iteration, 'b' is assigned with a value which is the opposite to itself... When 'i' is even... Output is not displayed, because b=false When 'i' is odd... Output is displayed, because b=true
31st Jul 2018, 3:39 PM
Nashat
Nashat - avatar
+ 1
it's just because of (b = !b), coz at every iteration you're assigning the opposite value of b.
19th Sep 2018, 4:06 AM
🇦 🇲 🇧 ✖️ ~𝓐𝓶𝓫𝓲𝓭𝓮𝔁𝓽𝓮𝓻𝓧 ▫️
🇦 🇲 🇧 ✖️ ~𝓐𝓶𝓫𝓲𝓭𝓮𝔁𝓽𝓮𝓻𝓧 ▫️ - avatar
0
This problem is somewhat misleading, especially to novice programmers. Starting from the answer itself, 13579, which has to be 1 3 5 7 9. In order to understand this problem and see what's going on under the hood, try to change the way the program outputs the answer on the screen by doing the following: for (int i = 1; i < 10; i += 2) { //System.out.printf("%d", i); System.out.println(i); } Now, your output should look like this: 1 3 5 7 9 It's just the difference between printf() and println(). The first prints i on the same line for each iteration and the result is 13579, while the latter prints the result for each iteration on a new line. So, the result 13579 has nothing to do with the number of iterations or the sum of i after executing the loop, because it's simply the numbers 1, 3, 5, 7, and 9 joined altogether on the same line! Try also the following: for (int i = 1; i < 10; i += 2) { System.out.printf("%d ", i); } The output now is: 1 3 5 7 9 I hope that helps..
8th Feb 2018, 7:53 PM
Embedded Guru
Embedded Guru - avatar
0
How about if i changed this if(b = !b) to this if( b = !true) aren't they same? boolean b = true;
25th Jul 2018, 11:02 AM
Said Boos
Said Boos - avatar