Let's just go back a moment, and think about you when you do a repetitive task: reading a book for example.
You start at the first page (page 1) and read that. then you turn the page, and read page two. Then you turn the page, and read page three. this continues until you have read the last page in the book, when you stop. That's all normal (except for those who read the end first to find out what happened, and we don't need them round here!)
So we can consider that in terms of a loop:
1) set pageNumber to 1
2) if pageNumber > numberOfPagesInTheBook then all done, we've finished the book
3) read page(pageNumber)
4) add one to pageNumber
5) go to (2)
So if we think about it, we have all four elements of the for loop:
Initialization:
1) set pageNumber to 1
Termination test:
2) if pageNumber > numberOfPagesInTheBook then all done, we've finished the book
Body:
3) read page(pageNumber)
Increment:
4) add one to pageNumber
Indicator that it's a loop:
5) go to (2)
So we can write that as a for loop:
for (int pageNumber = 1; pageNumber <= numberOfPagesInTheBook; pageNumber++)
read(PageNumber);
You can see that that does the same thing, it's just more compact!
When you process each string in an array you are doing the same thing:
String[] animals = {"Grizzly Bear", "Sloth", "SeaLion"};
for (int i = 0; i < animals.length; i++)
System.out.println(animals[i]);
1) Initialization: Create a variable which will change each time round teh loop, and set it to the first element:
for (
int i = 0
; i < animals.length; i++)
System.out.println(animals[i]);
2) Termination test: Have we processed the last row yet?
for (int i = 0;
i < animals.length
; i++)
System.out.println(animals[i]);
3) Body: Do something with each element:
for (int i = 0; i < animals.length; i++)
System.out.println(animals[i]);
4) Increment: move to next element:
for (int i = 0; i < animals.length;
i++
)
System.out.println(animals[i]);
Make sense?