Loops and Control Statements in Java


For while do...while

In this section we would discuss loops , control statements and decision making condition in java.  Always the loops and control statement are just explained as one of the language syntax. But there are so powerful in writing complex business logic. Breaking the loop using break and skipping the remaining part of loop statement by “continue” should be logical and succinct. Looping in programming languages is a feature which facilitates the execution of a set of lines repeatedly on some condition. Java provides three ways for executing the set of instruction repeatedly on some condition.

  • while
  • for and Enhanced for
  • do….while

while loop:

“while” loop allows code to be executed repeatedly based on a given Boolean condition. While loop executes set of lines until the Boolean condition becomes false. While loop check the boolean condition and if it evaluated to true, the set of lines in while loop body(code enclosed in{}). When the condition becomes false, the loop terminates which marks the end of its life cycle. One important design to consider in while loop is termination condition. The body of the while loop should have code to reach the termination condition or loop control statement such as “break” or “return”. Otherwise it would become infinite loop. while loop is best used in places where loop termination should occur based on input values or system behavior; Simply while loop can be used where we can’t determine the number of times execution of loop in advance.

Syntax :
while (boolean condition)
{
loop statements…
}

Keypoint to consider in while:

1). Ensure the body of loop has code lines to reach the termination condition.
2). boolean condition of the loop.
3). while loop is best fit if we could not determine the number of times execution of loop and it is decided based on input values or other external components.

for loop:

“for” loop provides a proper way of writing the loop structure as it has all the necessary artifacts of the loop in the syntax itself such as initialization condition, testing condition and code to reach termination of the loop. “for” loop is best fit if know the maximum number of execution of the loop.

Initialization condition: we initialize the variable in use. It marks the start of a for loop.
Testing Condition: Boolean condition which decide the execution of the loop. If it is true, the body of loop executed or loop would be terminated.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
Code to reach termination: Set of code to reach the termination of the loop. It is not only increment or decrements. Here any setup of code which help to reach the termination loop.

for (initialization condition; testing condition; code to reach termination of the loop){
statement(s)
}

Key-point to consider in while:

1). Ensure the code to reach termination of the loop is proper
2). Boolean condition of the loop.
3). for loop is best fit if we could determine the number of times execution of loop

Enhanced For loop:

Enhanced for loop is mostly widely used now and it is useful when you want to iterate Array/Collections. It is easy to write and understand. Will discuss more on enhanced for loop in java collection.Enhanced for loop is useful to iterate over all the element of the collections as below,

Let’s take the same example that we have written above and rewrite it using enhanced for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,21,45,9};
for (int num : arr) {
System.out.println(num);
}
}
}

Output:

2
21
45
9

The above both for and while loop are considered Entry condition loop as the boolean condition verified before the execution of the loop for and while. Comparison of for and while loop. In most of scenario while and for loop can be used interchangeably. Because it only different in the way of writing loop artifacts as shown below,

initialization condition;
while (testing condition){

loop statements…
code to reach termination of the loop;

}

for (initialization condition; testing condition; code to reach termination of the loop){

loop statements…

}

do while:

do while loop is similar to while loop with only difference that it checks for condition after executing the statements. So even the boolean condition false, the body of loop executed at-least once and it is call exit controlled loop.

Syntax:
do
{
statements..
}
while (condition);

Key points to consider:

do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements at-least once before any condition is checked, and therefore is an example of exit control loop.

Decision statements in Java:

1). if statement
2). if()…… else …… statement
2). if()…… else if()……else() statement

 

“if” statements: An if statement consists of a Boolean expression followed by one or more statements.

if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not, the first set of code after the end of the if statement (after the closing curly brace) will be executed.

int x = 10;

if( x < 20 ) {
System.out.print(“This is if statement”);
}

if…else:  if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Following is the syntax of an if…else statement −

if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}

If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

public class Test {

public static void main(String args[]) {
int x = 30;

if( x < 20 ) {
System.out.print(“This is if statement”);
}else {
System.out.print(“This is else statement”);
}
}
}

if..else if…else : if statement can be followed by an else if and an optional else statement, which executes when the Boolean expression is false.

Following is the syntax of an if…else statement −

if(Boolean_expression1) {
// Executes when the Boolean expression1 is true
}else if(boolean expression2) {
// Executes when the Boolean expression2 is true
}else{
// Executes when the all if loops conditions are false.
}

If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

public class Test {

public static void main(String args[]) {
int x = 30;

if( x < 20 ) {
System.out.print(“This is if statement”);
}else if(x == 20){
System.out.print(“This is else if statement”);
}else {
System.out.print(“This is else statement”);
}
}
}

Loop Control Statements:

  1. continue
  2. break

continue :

When a continue statement is encountered inside the body of a loop, remaining statements are skipped in the body of the loopa and loop proceeds with the next iteration.

public class ContinueExample {

public static void main(String args[]){
for (int j=1; j<=10; j++)
{
if (j%2 == 0)
{
continue; // It would continue for all even numbers
}

System.out.print(j+” “);
}
}
}

Output 1 3 5 7 9

break :

When a break statement is encountered inside body of the loop, the loop is terminated.

public class BreakExample {
public static final String CORRECTPASSWORD = “MYPASSWORD”;
public static void main(String args[]) {

Scanner in = new Scanner(System.in);
String password;
do {
System.out.println(“Enter a password : “);
password = in.nextLine();
if(password.equalsIgnoreCase(CORRECTPASSWORD)) {
break;
}
}while(!password.equalsIgnoreCase(CORRECTPASSWORD));
System.out.println(“your password is correct.”);
}
}

To write proper solution for complex problem and algorithm , we have to properly use the loop,decision statement and loop control statement properly. Let us write small algorithm to print number tower like below,

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Write java program to print this. Just think logic of loop and controls. The java code snippet for this algorithmas below,

int i=1;
while(i < 6) {
for(int j=1; j<6; j++) {
System.out.print( j +”\t”);
if(i==j) break;
}
System.out.println(“\n”);
i++;
}

You may also like