• 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

Enhansed For Loop Please explain me

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int [][]i={{1,2,3},{4,5,6}};
for (int []n: i)
/*This is single dimensional Array so how can you are accessing multi dimensional Arrays within Single dimensional Array.*/

for(int n2: i[2])
// what is this?
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The enhanced for loop is in the form of
for( declaration : expression ) { }
where
declaration declares a new variable (which typically will be used in the for loop)
and
expression must evaluate to an array of the type of the variable declared in declaration

In your first example, n is declared as a single dimensional array and the expression is a two dimensional array--which is an array of single dimensional arrays--so this meets the enhanced for loop specification.

In the second example, the expression "i[2]" is a single dimensional int array and n2 is an int, so again you are fine as far as the compiler is concerned. You will however get a runtime exception (ArrayIndexOutOfBoundsException) since i is only of length 2 (contains 2 int arrays) and therefore the maximum array index is 1.
 
I have always wanted to have a neighbor just like you - Fred Rogers. 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