Win a copy of Modern frontends with htmx this week in the Spring forum!
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic