No announcement
 

Loops

There are situations when we want to execute a block of code for a number of times. A loop construct allows us to execute certain piece of code several time.

while loop

The while loop executes a piece of code when the specified condition evaluates to true.

The structure of while loop is:

while (condition)
 {
    statement(s);
 }

As the program is executed line by line, first the condition is checked, if the condition evaluates to true, then only the piece of code specified after the condition is executed. If the condition evaluated to false, then the piece of code is skipped. We can say that while loop is an entry control loop.

Example:

WhileLoopDemo.java

package com.codingnous.tutorial;

public class WhileLoopDemo {

	public static void main(String[] args) {
		int counter = 1;

		// While loop.
		// Checking the value to be less then 10.
		// Increment the value by 1 if its below 10.
		while (counter < 10) {
			System.out.println("Counter value: " + counter + " is below threshold. Incrementing counter by 1.");
			counter++;
		}

		// This statement will be executed once the while loop is finished.
		System.out.println("Counter value: " + counter + " has reached threshold.");
	}
}

Output
Counter value: 1 is below threshold. Incrementing counter by 1. Counter value: 2 is below threshold. Incrementing counter by 1. Counter value: 3 is below threshold. Incrementing counter by 1. Counter value: 4 is below threshold. Incrementing counter by 1. Counter value: 5 is below threshold. Incrementing counter by 1. Counter value: 6 is below threshold. Incrementing counter by 1. Counter value: 7 is below threshold. Incrementing counter by 1. Counter value: 8 is below threshold. Incrementing counter by 1. Counter value: 9 is below threshold. Incrementing counter by 1. Counter value: 10 has reached threshold.

do while loop

If you want to make sure that the piece of code should be executed at least once, we need a construct where the condition is tested at the exit side. A do..while loop is such a construct.

The structure of do..while loop is:

do
 {
    statement(s);
 } while(condition)

As stated earlier, program is executed line by line, so when the piece of code is reached there is no condition test, hence the piece of code gets executed, but at the end is the condition test, if the specified condition evaluates to true then only the specified piece of code is executed again. We can say that the do..while loop is an exit control loop.

Example:

DoWhileLoopDemo.java

package com.codingnous.tutorial;

public class DoWhileLoopDemo {

	public static void main(String[] args) {

		int num = 1;

		do {
			System.out.println("Number is: " + num);
			num++;
		} while (num < 8);
	}

}

Output
Number is: 1 Number is: 2 Number is: 3 Number is: 4 Number is: 5 Number is: 6 Number is: 7

for & enhanced for loop

The for loop supports iteration controlled by a counter.

The structure of for loop is:

for(counter initialization; condition; counter update)
 {
    statements(s)
 }

Counter initialization is done first and only one time. After that boolean expression is evaluated. The piece of code specified in the body of for loop is executed if the specified condition evaluates to true. After execution of the piece of code, the loop jumps back to the counter update. If the condition evaluates to false, then the entire for loop is skipped and control move to the next statement.

Example:

ForLoopDemo.java

package com.codingnous.tutorial;

public class ForLoopDemo {

	public static void main(String[] args) {

		for (int counter = 1; counter < 10; counter++) {
			System.out.println("Current Iteration: " + counter);
		}
		System.out.println("Outside Iteration...");
	}

}

Output
Current Iteration: 1 Current Iteration: 2 Current Iteration: 3 Current Iteration: 4 Current Iteration: 5 Current Iteration: 6 Current Iteration: 7 Current Iteration: 8 Current Iteration: 9 Outside Iteration...

All the three parts i.e., counter initialization, condition and counter update are optional i.e, you can have:

for(;;)
 {
    statement(s);
 }

Skipping them can make the loop infinite.

An enhanced for loop or for each is used to traverse a collection of elements and arrays.

The structure of enhanced for loop is:

for(variable : collection or array)
 {
    statement(s)
 }

Example:

EnhancedForLoopDemo.java

package com.codingnous.tutorial;

public class EnhancedForLoopDemo {

	public static void main(String[] args) {

		// We will learn arrays later
		// Declare and initialize array with 8 elements
		int[] array = { 10, 11, 12, 8, 1, 2, 16, 14 };

		System.out.print("Array values are: ");

		// Print array values using enhanced for loop
		for (int val : array) {
			System.out.print(val + " ");
		}
	}
}

Output
Array values are: 10 11 12 8 1 2 16 14

break

A break statement can be used to terminate loop or switch statement immediately. The control moves to the immediate next statement after the loop or switch;

Example:

BreakStatementDemo.java

package com.codingnous.tutorial;

public class BreakStatementDemo {

	public static void main(String[] args) {

		int threshold = 5;

		// Start a loop for 10 times
		for (int counter = 1; counter <= 10; counter++) {
			System.out.println("Iteration: " + counter);

			// break from loop when current iteration equals the value of threshold.
			if (counter == threshold) {
				break;
			}

		}

		System.out.println("Iteration complete...");

	}

}

Output
Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Iteration: 5 Iteration complete...

continue

A continue statement causes the loop to skip the remaining piece of code and retest the condition prior to reiteration.

Example:

ContinueStatementDemo.java

package com.codingnous.tutorial;

public class ContinueStatementDemo {

	public static void main(String[] args) {

		int threshold = 2;

		// Start a loop for 4 times
		for (int counter = 1; counter <= 4; counter++) {
			System.out.println("Iteration: " + counter);

			// Continue when current iteration equals the value of threshold.
			if (counter == threshold) {
				// Rest of the statements will not be executed after this.
				continue;
			}

			System.out.println("Last message.");

		}

		System.out.println("Iteration complete...");

	}

}

Output
Iteration: 1 Last message. Iteration: 2 Iteration: 3 Last message. Iteration: 4 Last message. Iteration complete...