Wednesday, June 6, 2012

FOR LOOP

  • For loop executes group of Java statements as long as the boolean condition evaluates to true.
For loop combines three elements which we generally use: initialization statement, boolean expression and increment or decrement statement.
For loop syntax
for( <initialization> ; <condition> ; <statement> ) 
{
        <Block of statements>;
}

  • The initialization statement is executed before the loop starts. It is generally used to initialize the loop variable.
  • Condition statement is evaluated before each time the block of statements are executed. Block of statements are executed only if the boolean condition evaluates to true.
  • Statement is executed after the loop body is done. Generally it is being used to increment or decrement the loop variable.
It is possible to initialize multiple variable in the initialization block of the for loop by separating it by comma as given in the below example.
  1. for(int i=0, j =5 ; i < 5 ; i++)

It is also possible to have more than one increment or decrement section as well as given below.
  1. for(int i=0; i < 5 ; i++, j--)

However it is not possible to include declaration and initialization in the initialization block of the for loop. Also, having multiple conditions separated by comma also generates the compiler error. However, we can include multiple condition with && and || logical operators.

PROGRAM:

/*PROGRAM TO PRINT EVEN NUMBERS*/
public class ListEvenNumbers
 {
        public static void main(String[] args)  
         {
                int limit = 50;    
                System.out.println("Printing Even numbers between 1 and " + limit);
                for(int i=1; i <= limit; i++) 
                 {
               // if the number is divisible by 2 then it is even
                      if( i % 2 == 0)
                     {
                                System.out.print(i + " ");
                      }
                }
        }
}

TRY YOURSELF:8
1)Write a program to print odd numbers between 1 and 20 using for loop.

No comments:

Post a Comment

Animated Social Gadget - Blogger And Wordpress Tips