| Home | Links |

For Loops

  • all the pieces of loop are compacted into one line 
  • pretest loops
  • tests the loop condition before executing the loop body
  • might not execute the loop body
  • executed a predetermined number of times

General Formula

for (starting integer; Boolean test; moving to stopping condition)
{

Statement or block;

}

Examples

for (int x = 0 ; x < 10 ; x++)
{

System.out.print (x + " ");

}

Prints out: 0 1 2 3 4 5 6 7 8 9

 

for (int x = 0 ; x < 10 ; x+=2)
{

System.out.print (x + " ");

}

Prints out: 0 2 4 6 8


for (int x = 3 ; x <= 10 ; x++)
{

System.out.print (x + " ");

}

Prints out: 3 4 5 6 7 8 9 10

 

for (int x = 10; x > 0 ; x--)
{

System.out.print (x + “ “);

}

Prints out: 10 9 8 7 6 5 4 3 2 1