loop with for statement

The statement loop allows the program repeat the same action multiple times. When you know in advance how many times this action has to be repeated, you can use a loop with a keyword for:

The forloop is written as below, for example

for (i=0;i < 10; i++){

i is a counter, i<10 is a precondition; only if i<10, the step is executed. When can see the loop is going through 0,1,2,3,4,5,6,7,8,9.

There is another flavor of the for loop known as for each loop. It allows the program to repeat the same action to every element of the collection without even knowing how many are there. You are basically saying, do this for each element. For example, we have a collection as students. To every student of the students, the action the repeated.

for (String student: students){

Let's make a practice in class dog, if a dog needs to bark "arf" for several times, 
the printing code should be invokes several times in a loop. 

In DogMaster Class, you can try to change the repeatTimes to see how many "arf" are printed out.
From console, you can see the output:




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s