While Statement in Java

The simplest of all the looping structures in java is the while statement.The basic format of the while statement is:-

Initialisation:

while(test condition)

{

       body of the loop

}

      The while loop is an entry -controlled loop statement.The test condition is evaluated and if the condition is true ,then the body of the loop is executed.After execution of the body,the test condition is once again evaluated an if it is true,the body is executed once again.This process of execution of the body of the body continues until the test condition becomes false and the control is transferred out of the loop.On exit,the program continues with the statement immediately after the body of the loop. The body of the loop may have one more statements.

Consider the following example:-

 

………………..

………………..

sum=0;n=1;while(n<=10)

{

          sum=sum+n*n;

           n=n+1;

}

 

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

………………

……………..

The body of the loop is executed 10 times for n=1,2,3…..,10 each time adding the square of the value of n,which is incremented inside the loop.The test condition may also be written as n<11;the result would be the same.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s