5. Java – Simple Loop

public class HelloWorld {
     public static void main(String[] args)
     {
         //Print name 10 times.
         int i = 0;
         // for(initialization;condition;increment)
         for(i=0;i<10;i++)
         {   
           System.out.println("Tiger : "+Integer.toString(i));
         }
 } 
}

Note – a for loop has 3 parts.

  1. Initialization – use a variable like i = 0.

2. Condition – how long should loop continue ?. in this case if i < 10. as soon as i is above 10 loop will exit.

3. Increment/Decrement – need to increment or decrement i. else loop will go for ever.

Finally – we cannot print i directly in println as its a integer and hence the conversion using Integer.toString( ). Println, print function is for strings and characters.

Output:

%d bloggers like this: