Saturday 12 March 2011

Decision making and looping

INTRODUCTION:
The iteration statements aloow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Java provides three kinds of loops:
  • While loop
  • do-while loop
  • for loop
All three constructs of java repeat a set of statements as long as a specified condition remains true. The specified condition is generally referred to as a loop control. For all three loop statements, a true condition is any nonzero value. A zero value indicates a false condition.

THE WHILE STATEMENT:
The most simple and general looping structure available in java is the while statement. The syntax of while loop is:
   while(condition)
   {
      // loop-body
    }
Where the loop body may contain a single statement, a compound statement or an empty statement. The loop iterates while the condition evaluates to true. When the expression becomes false, the program control passes to the line after the loop body code.

//program for while loop

class whiletest
 {
    public static void main(String args[])
      {
         int n=10;
         while(n>0)
         {
           System.out.println("tick", +n);
           n--;
          }
       }
}

THE DO STATEMENT:
Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom of the loop after executing it's loop-body statements. This means that a do-while loop always executes at least once. The syntax of the do-while loop is:
    do
    {
         loop-body;
     }
while(condition);

Example: 
 Class doWhileCheck
  {
     Public static void main (String args[])
      {
         int n=10;
          do
            {
               System.out.println("tick" +n);
                n--;
            }
             while(n>0);
        }
   }
THE FOR STATEMENT:
The for loop is the easiest to understand of the java loops. All its loop-control elements are gathered in one place (on the top of the loop), while in the other loop construction of C++ , they( top-contol elements) are scattered about the program. The Syntax of the for loop statement is:

for( initialization expression(s); test condition; update expression)
{
   loop-body;
}

//program showing usage of for loop
class forTest
{
   public static void main(String args[])
 {
    int i;
    for( i=1; i<=10; i++)
     System.out.println(i);
 }
}

Following figure outlines the working of a for loop:

Execution of a for loop
 


1 comment: