Loop
In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
Types of Loop in Java are given below:
The while loop
The while statement continually executes a block of statements while a particular condition is true.
Its syntax can be expressed as:
while (expression) {
statement(s)
}
Example:
class Kalokalam {
public static void main(String[] args) {
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
Do-while loop
The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
statement(s)
}
while (expression);
Example:
class Kalokalam{
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
For loop
Syntax:
for (initialization; condition; increment/decrement) {
statement(s) //block of statements
}
Example:
class ForLoopExample {
public static void main(String args[]) {
for (int i = 10; i > 1; i--) {
System.out.println("The value of i is: " + i);
}
}
}
Example 2:
class tra2 {
public static void main(String args[]) {
int x, y;
for (x = 1; x < 10; x++) {
for (y = 0; y < x; y++) {
System.out.print("*");
}
System.out.println("");
}
}
}
Output:
*
**
***
****
*****
******
*******
********
*********
Break Statement:
The break statement is used to exit or terminate the execution of a loop or a switch statement. When encountered, it immediately exits the enclosing loop or switch statement, and the program continues with the next statement after the loop or switch. It helps in prematurely exiting a loop or stopping the execution of further cases in a switch statement.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is equal to 5
}
System.out.println(i);
}
Output:
1
2
3
4
Continue Statement:
The continue statement is used to skip the current iteration of a loop and continue with the next iteration. When encountered, it immediately jumps to the next iteration without executing any further statements in the loop’s body. It allows skipping specific iterations based on certain conditions.
Example of continue statement in a loop:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i is equal to 3
}
System.out.println(i);
}
Output:
1
2
4
5