Difference between revisions of "For Tutorial"

From Progzoo
Jump to: navigation, search
Line 10: Line 10:
 
:Test - the loop executes only if the test is passed.
 
:Test - the loop executes only if the test is passed.
 
  i<10
 
  i<10
:Iteration - this happens after each step.
+
:Iteration - this happens after each step. In this case i++ means increase i by one.
 
  i++
 
  i++
 
:Body - this is the bit that gets executed each time, the body is alway indented
 
:Body - this is the bit that gets executed each time, the body is alway indented
 
  System.out.println(i);
 
  System.out.println(i);
 
+
Putting it together the loop says:
 +
:Start by setting i to 0
 +
:Print the value i
 +
:increase i - from 0 to 1
 +
:Print i
 +
:increase i - now i is 2
 +
:Print i
 +
:increase i - now i is 3
 +
:Print i
 +
:increase i - now i is 3
 +
:Print i
 +
:increase i - now i is 4
 +
:Print i
 +
:increase i - now i is 5
 +
:Print i
 +
:increase i - now i is 6
 +
:Print i
 +
:increase i - now i is 7
 +
:Print i
 +
:increase i - now i is 8
 +
:Print i
 +
:increase i - now i is 9
 +
:Print i
 +
:increase i - now i is now 10, it fails the test i<10 and so the loop halts.
 
[[Category:Tutorial]]
 
[[Category:Tutorial]]

Revision as of 19:03, 24 September 2008

You can use the for loop to make a section of code repeat many times.

for (int i=0;i<10;i++)
  System.out.println(i);

The line System.out.println(i); happens 10 times.

There are four parts to the structure:

Initialization happens once at the start of the loop
int i=0;
Test - the loop executes only if the test is passed.
i<10
Iteration - this happens after each step. In this case i++ means increase i by one.
i++
Body - this is the bit that gets executed each time, the body is alway indented
System.out.println(i);

Putting it together the loop says:

Start by setting i to 0
Print the value i
increase i - from 0 to 1
Print i
increase i - now i is 2
Print i
increase i - now i is 3
Print i
increase i - now i is 3
Print i
increase i - now i is 4
Print i
increase i - now i is 5
Print i
increase i - now i is 6
Print i
increase i - now i is 7
Print i
increase i - now i is 8
Print i
increase i - now i is 9
Print i
increase i - now i is now 10, it fails the test i<10 and so the loop halts.