For Tutorial

From Progzoo
Revision as of 09:05, 28 September 2015 by Andr3w (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
<< Boxes Tutorial

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

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








0
1
2
3
4
5
6
7
8
9

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. The loop will complete when i reaches the value 10.
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 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.