0% completed
The for loop in Java is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of iterations. It is especially useful when you know in advance how many times you want the loop to run.
The for loop consists of three parts:
These parts are specified within the loop's header and help manage the loop's behavior.
for (initialization; condition; update) { // Code block to be executed }
Below is an example that uses a for loop to print numbers from 1 to 5.
Explanation:
int i = 1
sets the starting value of the loop counter to 1.i <= 5
checks if i
is less than or equal to 5 before each loop iteration.i++
increments the value of i
by 1 after each iteration.i
becomes 6.Below is an example that uses a for loop to calculate the sum of the first 5 positive integers.
Explanation:
int i = 1
starts the loop counter at 1.i <= 5
.i++
increases the counter by 1 after each iteration.i
is added to sum
.The for loop is a powerful construct for repeated execution. By understanding its structure—initialization, condition, and update—you can control the loop's behavior effectively.
.....
.....
.....