Java From Beginner To Advanced

0% completed

Previous
Next
Java for Loop

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:

  • initialization
  • condition
  • update.

These parts are specified within the loop's header and help manage the loop's behavior.

Syntax

for (initialization; condition; update) { // Code block to be executed }
  • Initialization: Executed once at the start; used to set the loop counter.
  • Condition: Evaluated before each iteration; if it evaluates to true, the loop body executes.
  • Update: Executed at the end of each iteration; typically used to increment or decrement the counter.

Execution Flow of For Loop

Image
  • Step 1: The initialization step is executed before the loop starts.
  • Step 2: The condition is checked. If it is true, the loop's body executes.
  • Step 3: After the code block executes, the update step is performed.
  • Step 4: The condition is checked again. If still true, the loop repeats the process. This continues until the condition becomes false.
  • Step 5: Once the condition is false, the loop terminates and control moves to the next statement after the loop.

Example 1: Basic for Loop

Below is an example that uses a for loop to print numbers from 1 to 5.

Java
Java

. . . .

Explanation:

  • Initialization: int i = 1 sets the starting value of the loop counter to 1.
  • Condition: i <= 5 checks if i is less than or equal to 5 before each loop iteration.
  • Update: i++ increments the value of i by 1 after each iteration.
  • The loop prints "Number: 1" up through "Number: 5" and then terminates when i becomes 6.

Example 2: Using a for Loop to Sum Numbers

Below is an example that uses a for loop to calculate the sum of the first 5 positive integers.

Java
Java

. . . .

Explanation:

  • Initialization: int i = 1 starts the loop counter at 1.
  • Condition: The loop continues as long as i <= 5.
  • Update: i++ increases the counter by 1 after each iteration.
  • In each iteration, the current value of i is added to sum.
  • After finishing the loop, the sum (which is 15) is printed.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next