Java For Loop

 

 

Java  for  loop  is  used,  when  you  know  exactly  how  many  times  you  want   to  loop  through  a  block  of  code. 

 

 

 

Syntax  of  For  Loop :

 

 

for ( initialization ;  condition ; increament/decrement  ) {

       //code  to  be  executed  repeatedly

}

 

 

 

initialization :   This  initialisation  statement  is  executed  once  at  the  beginning  of  the  loop  which  is  used  to   declare  and  initialize  a  loop  control  variable .

Example:  int  i= 0 ;

 

 

condition :   This  condition  statement  which  is  of  type  boolean  is  evaluated  before  each  iteration  of  the  loop . If the  condition  evaluates  to  be  true, the  block  of  code  within the  for  loop  is  executed . If  it  is  false , the loop  terminates.

 

Example : i<5 ;

 

 

increment/decrement :  This  increment or  decrement  statement  is  executed  after  each  iteration of  the  loop . It  is  mostly  used  to  update  the  loop  control  variable.

 

Example :   i++   or  i—;

 

 

 

 

 

Example  of  for  Loop :

 

Example1:   Print  numbers  from  1  to   5  using  for  loop.

 

for ( int i= 1; i<=5; i++ )  {

System.out.println (i);

}

 

Example 2 :   Print  the  even  numbers  between  0  and 15

 

 for ( int i=0 ; i <=15 ; i=i+2 ) {

  System.out.println(i);

}

 

 

 

 

Example 3 :    Print  the  sum  of  numbers   from  1  to  7  using  for  loop

 

 

int  sum=0;

for ( int i=1 ; i <= 7 ; i++ ) {

sum=sum+i;

}

System.out.println(” Sum  is : “+sum);

 

 

 

 

Example 4 :  Prints  a  countdown  from  7  to  1 :

 

 

 

for ( int i=7 ; i>0 ; i– ) {

  System.out.println(i);

 

}

 

 

 

 

For  Loop  with  False  Condition :    If  the  condition  inside  a  for  loop  is  false  from  the  start, the  code  inside  the  for loop  will  be  skipped  entirely .

 

 

 

Example :

 

for ( int i=7 ;i<3;i++ ){

  System.out.println(“This will  never  print  as  condition  inside  this  for loop  is  false “);

}

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *