- For loop: A for loop is used when you know how many times you want to execute a block of code. The basic syntax of a for loop is as follows:
for (initialization; condition; increment) {
// code to execute repeatedly
}
Here, initialization
is an expression that initializes a variable used in the loop, condition
is an expression that is evaluated before each iteration of the loop, and increment
is an expression that is executed after each iteration of the loop. The loop will continue to execute the block of code within the curly braces as long as the condition
is true.
For example, consider the following code that uses a for loop to print the numbers from 1 to 5:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
In this case, the initialization
statement initializes the variable i
to 1, the condition
statement specifies that the loop should continue as long as i
is less than or equal to 5, and the increment
statement increments i
by 1 after each iteration of the loop.