Gadgets

Showing posts with label for loop. Show all posts
Showing posts with label for loop. Show all posts

Tuesday, 24 November 2015

for loop Program in java

For loop Program in java
  1. for loop is the loop statement in java programming and for loop is used to execute set of statements until the condition is true.
  2. for loop checks the contrition and executes the set of the statements.
  3. for loop contain the following statements such as “Initialization”, “Condition” and “Increment/Decrement” statement.
for(var-initialization; condition; increment/decrement)


For loop Example:
public class ForLoopTest {
    public static void main(String a[]){
        int i;
        for(i=1;i<=5;i++){
            System.out.println(i);
        }
    }    
}
Output:
1
2
3
4
5 
Error free example:
It is an error free but it prints infinite numbers 
public static void main(String a[]){
        boolean exp = true;
         for(int i=1; exp ; i++){
              System.out.println(i);
         }
    }
Compile time error:
It gives compile time error because int exp = true;. Here data type is int value is boolean(true) 
public static void main(String a[]){
        int exp = true;
         for(int i=1; exp ; i++){
              System.out.println(i);
         }
    }
For each loop:
For-each loop introduced in java5 version, it is an advanced of for loop and it is more reliable.
public class ForeachLoop {
   public static void main(String args[]){  
   int a[]={10,20,30,40};
   for(int i:a){  
   System.out.println(i);  
   }   
 }       
}
Output:
10
20
30
40