• 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
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Arrays

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.
 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
see te following part of code and its execution

{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;

}

a[1]=0 ---> {1,0,3,4}
a[0]=0 --->{0,0,3,4}
a[3]=0 ---> {0,0,3,0}
a[0]=0 --->{0,0,3,0}

iterate through the loop and print the value which gives 0030

Hopw this helps you.

Geeta Vemula
 
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Abhi vijay:
Source:John Meyers Mock test

class P3
{
public static void main(String[] args)
{int []arr = new int[]{1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}
for ( int i : arr )
{
System.out.println(i);
}
}
}

The answer is 0030.Can anyone expalin.



Hi abhi here is explaination :

Intial Values:
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4

Now, how for loop executes:
1) step
i=arr[0]=1
that means =>arr[i]=arr[1]=0
arr[0]=1
arr[1]=0 <--- Effected
arr[2]=3
arr[3]=4

2) step
i=arr[1]=0
that means =>arr[i]=arr[0]=0
arr[0]=0 <--- Effected
arr[1]=0
arr[2]=3
arr[3]=4

3) step
i=arr[2]=3
that means =>arr[i]=arr[3]=0
arr[0]=0
arr[1]=0
arr[2]=3
arr[3]=0 <--- Effected

now Just print in next for looop.
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot guys.
 
Politics n. Poly "many" + ticks "blood sucking insects". 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