Смарт контракты

Published 15 October 2018

Loops and loop statements in Java

What are loops in Java

What are loops in Java

A loop is a control construct of a Java programming language designed to execute a set of instructions multiple times. The following types of loops exist in the Java language: for, for-each, while, do-while.

For, for-each loop

For, for-each loop

The for loop is the most common loop, and its construct looks as follows:

for ([initialization]; [condition]; [iteration])

{

// actions

}

Initialization — contains the variable and its initial value. Condition is the Boolean expression at which the loop will be executed. Iteration is an expression that modifies the initialization variable after each step of the loop.

Example:

for (int i = 1; i <=15; i++){

System.out.println(i);

}

The for-each loop is a type of a for loop used to iterate through the elements of an array, a collection. It has the following construct:

for (data type variable_name : array/collection name){

// actions

}

Example:

int[] k = {98,23,65,77,1,7,845};

for (int j:k) {

System.out.println(j);

}

While loop

While loop

The while loop is a loop with a precondition that verifies the truth of the condition, and if the condition is true, the loop code is executed. It has the following construct:

while ([condition]) {

//cycle body

}

Example:

int i=0;

while (i<6) {

i++;

System.out.println(i);

}

Do-while loop

Do-while loop

The do-while loop is a loop with postcondition, it executes the loop body first and then validates the condition. It has the following construct:

do {

//cycle body

} while ([condition]);

Example:

int i=0;

do {

i++;

System.out.println(i);

} while (i<10);

Break, continue statements

Break, continue statements

Break statement, which is an early exit from a loop, is placed inside the loop body, when the break statement is executed, the loop is immediately exited, and control is passed to the statement following the loop.

Continue statement is used inside the loop body, calling the loop to move to the next iteration.

Votes 0, average rating 0

Contents