JAVA FLOW CONTROLS – PART 2

In the previous part we learned about the Selection flow controls. Moving further, today we are going to look at the other flow control type which is Iteration.

There are three types of Iteration algorithms.

  1. while
  2. do while
  3. for

1.while

In this algorithm, the program runs till the condition in the parameter list becomes false. After executing the statements within the while block, it runs back to the condition.

Ex :

int i = 0;

while(i<=2){

System.out.println(i);

i++;

}

The output in the above example is 0,1 and 2. 3 is not printed since 3 is not satisfying the condition.

2.do while

In this scenario, it is a bit same as while, but the main difference is the statement inside the do block is executed at least once whether the condition in the parameter list of while is true or false.

Ex :

int i = 0;

do {

System.out.println(i);

} while(i>=1);

The output in the above scenario is 0 which means the do block is executed once although the condition is false.

3.for

For loop is a descriptive loop with a parameter list which contains variable declaration and initialization, condition and iterative statement. After executing the statements within the for block, the program runs back to the iterative statement.

Ex :

for(int i=0;i<10;i++){

System.out.println(i);

}

The output in the above scenario is 0,1,2,3,4,5,6,7,8,9. When the value of i changes to 10, the condition becomes false and loop is terminated.

So now, we have come to the end of basic Java flow controls and hope you all learned at least a small thing. Happy coding !!!!!

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s