Tuesday, January 4, 2011

Understanding do while loop in BlueJ

It is observed that students mostly use for loop or while loop whenever loop execution is necessary in a program. If they are asked about their favorite loop, I am sure most of them will go with for loop and then major part of the rest will favors while loop.

We know that any type of loop can perform any type of job. There is no difference in using any type of loop in any program. Still do while loop has got some unique features which make it different from the other two types of loop. Firstly, do while loop is an exit control loop which indicates that the conditional statement will be executed at the end of loop body. This feature helps us to start the loop execution without initializing the loop control variable before the first execution of the loop. In such case when the do while loop executes for the first time, the loop control variable gets initialization and afterwards during iterations, it gets reinitialized.

Syntax of do while loop



Do while loop starts with the keyword ‘do’ and ends with the keyword ‘while’. Like other loops, we have to put curly braces in between ‘do’ and ‘while’ to define the body of loop if the loop body contains more than one statement. One important point to be kept in mind that ‘while’ is the control statement of do while loop and after this statement a semicolon is a must.

do
{
Body statement(s)
Re initialization
} while (condition);

Program using do while loop

This program is as stated below:
Take ‘n’ numbers from the user and display the total even numbers entered by the user.

import java.io.*;
class Test
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show()throws Exception
{
String ans;
int i,c=0;
do
{
System.out.println("Enter a number:");
i=Integer.parseInt(br.readLine());
if(i%2==0)
c++;
System.out.println("Any More (Yes/No):");
ans=br.readLine();
} while(!ans.equalsIgnoreCase("NO"));
System.out.println("Total even numbers entered="+c);
}
public static void main(String args[])throws Exception
{
new Test().show();
}
}

Here the loop control variable is a String class object ‘ans’. Note that ‘ans’ is not initialized before the start of the do while loop. The loop executes for the first time without any checking and performed the job assigned within its body. At the end of the loop body user’s choice is taken and assigned on ‘ans’ and this is initialization of loop control variable. From the second iteration of the loop, ‘ans’ is reinitialized.

The basic difference between entry control loops and do while loop

In entry control loops, loop control variables are initialized before the looping cycle starts whereas in do while loop we can leave the initialization process for the body statements of the loop. Sometimes in do while loop initialization of loop control variable is needed above the loop body. One such example of do while loop is given below.

In this program, user will enter two numbers and the result of first number divided by the second number will be displayed. This process will continue for ‘n’ times.

import java.io.*;
class Test
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show()throws Exception
{
String ans;
int a,b,r,c=0;
do
{
System.out.println("Enter 1st number:");
a=Integer.parseInt(br.readLine());
System.out.println("Enter 2nd number:");
b=Integer.parseInt(br.readLine());
if(b==0)
continue;
r=a/b;
System.out.println("Result:"+r);
System.out.println("Any More (Yes/No):");
ans=br.readLine();
}
while(!ans.equalsIgnoreCase("NO"));

}
public static void main(String args[])throws Exception
{
new Test().show();
}
}

On compilation error will be shown ‘variable ans might not have been initialized’.

Why this happens?

‘continue’ statement is used in the do while loop of this program and it is required. If the entered second number becomes zero then a run time error would be flagged. To overcome such situation, continue is used. When this continue statement in do while loop is encountered, it sends the control to the control statement. For this reason, the loop control variable needs initialization above the loop body although it’s a do while loop.

Necessary change needed is to initialize the loop control variable where it is declared. Within show () function modify the statement ‘String ans’ with String ans=”y”

1 comment:

  1. Thanks! :D This was really helpful. Starting right now I'm gonna bookmark this page (and all other pages related to Bluej) Now I'll finally ace those tests. Gonna start reviewing now :)

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner