• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Why will I get this output?

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!!
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
He puts the "turd" in "saturday". Speaking of which, have you smelled this tiny ad?
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic