Difference between revisions of "For Tutorial"

From Progzoo
Jump to: navigation, search
Line 2: Line 2:
 
You can use the <code>for</code> loop to make a section of code repeat many times.
 
You can use the <code>for</code> loop to make a section of code repeat many times.
 
{|
 
{|
 +
!Program Code
 +
!Output
 +
|-
 
|
 
|
 
  for (int i=0;i<10;i++)
 
  for (int i=0;i<10;i++)

Revision as of 19:07, 24 September 2008

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.
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.