loops in java

Posted By on September 12, 2014


Download PDF
The this keyword
foreach loop in JAVA

There may be a situation when we have to execute a block of program several times.  This situation is referred to as looping.

Java supports three loops::

1. for loop

2. while loop

3. do…while loop

These are the basic loops that we studied in c/c++.

1. for loop::

A for loop is a repetition control structure that allows you to execute a block of program for a finiti time.

It can be used when you know how many times you want to execute the block.

The basic syntax is::

for(initialization; boolean_expression; update)

{

// program  //

}

The  initialization  step  is  executed  first,  and  only  once.  This  step allows you to declare and  initialize any loop  control  variables. Youare  not  required  to  put  a  statement  here,  as  long  as  a  semicolonappears.

Next,  the  Boolean  expression  is  evaluated.  If  it  is  true,  the  body of the loop is executed. If it is false, the body of the loop does not execute  and  flow  of  control  jumps  to  the  next  statement  past  the for loop.

After  the  body  of  the  for  loop  executes,  the  flow  of  control  jumps back  up  to  the  update  statement.  This  statement  allows  you  to update  any  loop  control  variables.  This  statement  can  be  left blank,  as  long  as  a  semicolon  appears  after  the  Boolean expression.

The  Boolean  expression  is  now  evaluated  again.  If  it  is  true,  the loop  executes  and  the  process  repeats  itself  (body  of  loop,  then update  step,  then  Boolean  expression).  After  the  Boolean expression is false, the for loop terminates.

 

2. while loop::

 

A while loop is a control structure that allows you to repeat a task a certain number of times.

The basic syntax is::

while(boolean_expression)

{

// program //

}

When executing, if the boolean_expression result is true, then the actions  inside the  loop will be executed. This  will continue as  longas the expression result is true.

Here,  key  point  of  the while loop  is  that  the  loop  might  not  ever run.  When  the  expression  is  tested  and  the  result  is  false,  the loop  body  will  be  skipped  and  the  first  statement  after  the  while loop will be executed.

 

3. do…while loop::

A  do…while  loop  is  similar  to  a  while  loop,  except  that  a do…while loop is guaranteed to execute at least one time.

The basic syntax is::

do{

// program //

}while(boolean_expression);

The this keyword
foreach loop in JAVA

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com