Wednesday 5 February 2014

Control flow statements : looping : for

The for statement provides a compact way to iterate over a range of values.

Syntax
    for(initialization; condition; update){
        //statements to be executed
    }

for loop execute the statements until the condition evaluates to false.

Initialization section executed only once, at the starting of loop.
Condition section evaluated every time, before executing the loop statements
update section executes immediately after every execution of loop finishes.

Example : Printing numbers from 0 to 9
class ForEx{
 public static void main(String args[]){
  int var1;
  for(var1 = 0; var1 < 10; var1++){
   System.out.println(var1);
  }
 }
}

Output
0
1
2
3
4
5
6
7
8
9
Some points to remember
1. You can declare a variable inside the for loop itself
        for(int i=0; i<10; i++) is a valid construct

2. for( ; ; )
     Above for loop run for infinite times.


loops                                                 break statement                                                 Home

No comments:

Post a Comment