![]() |
VOOZH | about |
The for loop in Java is a control flow statement used to execute a block of code repeatedly based on a condition. It is especially useful when the number of iterations is known in advance, such as iterating over a range of values, arrays, or collections.
Example:
1 2 3 4 5 Loop has ended.
Explanation:
for (initialization; condition; update) {
// loop body
}
Working:
The following examples demonstrate how for loops and nested for loops are used in Java for iteration, pattern printing, and calculations.
Example 1. Printing "Hello World" Multiple Times
Hello World Hello World Hello World Hello World Hello World
Sum: 210
A nested for loop is a loop inside another loop. It is commonly used for matrix operations and pattern printing.
Example: Printing a Matrix-like Pattern
(1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
Note: To know more about Nested loops refer Nested loops in Java.
An infinite for loop occurs when the loop condition never becomes false.
Output:
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
...
Note: A "Time Limit Exceeded" error occurs when a program runs longer than the time allocated for execution, due to infinite loops.