+ 8

Dear Solo friends, could anyone explain me the output of this code, please?

int[] a = {1, 2, 3, 4, 1}; for(int n:a) a[n]=0; for(int n:a) System.out.println(n); The output is 00301 I thought, that the answer is 00000, but it is wrong.

14th Apr 2018, 8:33 PM
Ulyana Sveleba
Ulyana Sveleba - avatar
2 odpowiedzi
+ 5
Xan thankyou very much for your answer Xan. It makes sense for me now 🙄 Talking about braces and identations, I try to use them whenever possible because I find the code without them less readable, too. It's just a code from a challenge question and I didn't want to change anything in it. thankyou again!
15th Apr 2018, 12:26 PM
Ulyana Sveleba
Ulyana Sveleba - avatar
+ 1
Always put debug output in your code to find problems: https://code.sololearn.com/cKqxaOzM8GX1/?ref=app Your first for loop is doing this: a[1] = 0; a[0] = 0; a[3] = 0; a[0] = 0; a[1] = 0; Meaning a[2] and a[4] remain unchanged. Also, always use braces, and identation. It won't slow down the execution of code, and it's a lot more readable.
14th Apr 2018, 10:23 PM
Emma