Java From Beginner To Advanced

0% completed

Previous
Next
Java while Loop

The while loop in Java repeatedly executes a block of code as long as a given condition remains true. It is useful when you don't know in advance how many iterations are needed, and the loop continues until the condition fails. The while loop checks its condition before each iteration, ensuring the code inside the loop only runs when the condition is satisfied.

Syntax

while (condition) { // Code block to be executed }
  • condition: A boolean expression that is evaluated before each iteration.
  • Code block: Contains the statements to execute as long as the condition is true.

Execution Flow

Image
  • Step 1: The condition is evaluated before entering the loop.
  • Step 2: If the condition is true, the loop's code block is executed.
  • Step 3: After executing the block, the condition is evaluated again.
  • Step 4: Steps 2 and 3 repeat until the condition evaluates to false, at which point the loop terminates and control passes to the next statement after the loop.

Example 1: Counting Using a While Loop

Below is an example that demonstrates using a while loop to print numbers from 1 to 5.

Java
Java

. . . .

Explanation:

  • The loop starts with count equal to 1 and prints the value as long as count is less than or equal to 5.
  • Each iteration increments count by 1, and the loop terminates when the condition becomes false.

Example 2: Summing Numbers Using a While Loop

Below is an example that uses a while loop to calculate the sum of numbers from 1 to 5.

Java
Java

. . . .

Explanation:

  • The while loop continues to add numbers to sum as long as number is less than or equal to 5.
  • After each addition, number is incremented until the condition fails, and the final sum is printed.

By mastering the while loop, you gain flexibility in handling situations where the number of iterations is not predetermined. Experiment with these examples to see how while loops can effectively manage repeated actions based on dynamic conditions.

.....

.....

.....

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