Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why will I get this output?

 
Jayes Herryl
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

Could someone help to explain why I am getting such output from running this piece of code?

class Test{
public static void main(string[] args){
int[] arr = {1, 2, 3, 4};
for(int i : arr) {
arr[i] = 0;
System.out.println(i + " " + arr[i]);
}
for(int i : arr)
System.out.print(i);
}
}
OUTPUT:
1 0
0 0
3 0
0 0
0030

How come the first loop gives 1 as the first value for i and gives 0 to the first i at the second loop? After the first loop, elements in arr are all initialized to zero, then why shouldn't the second loop output 0000??
Is it because i is not initialized?

Thanks for any advice in advance!!
 
Michael Valentino
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<hr></blockquote>

first loop:
in the first iteration, i is assigned the value of arr[0], which is 1. the line arr[i] = 0 is executed, so now arr[1] = 0. arr is now {1, 0, 3, 4 }. The output to the screen is: 1 0

Second iteration, i = arr[1], so i = 0. arr[i] = 0 executes so now arr[0] = 0. arr is now {0, 0, 3, 4 }. The output to the screen is: 0 0

Third iteration: i = arr[2] so i = 3. arr[i] = 0 executes so now arr[3] = 0. arr is now {0, 0, 3, 0}. The output to the screen is: 3 0

Last iteration: i = arr[3] so i = 0. arr[i] = 0 executes so arr[0] = 0. arr is now {0, 0, 3, 0}. The output to the screen is: 0 0


Finally, the second for loop executes and prints out the modified array. In the code, at each iteration, i is assigned the next value of arr[]. If you followed the first loop, the values in the array at this point should be clear: 0030.

So the final output should look like this:


Make sense?
[ June 13, 2006: Message edited by: Michael Valentino ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic