0% completed
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.
while (condition) { // Code block to be executed }
Below is an example that demonstrates using a while loop to print numbers from 1 to 5.
Explanation:
count
equal to 1 and prints the value as long as count
is less than or equal to 5.count
by 1, and the loop terminates when the condition becomes false.Below is an example that uses a while loop to calculate the sum of numbers from 1 to 5.
Explanation:
sum
as long as number
is less than or equal to 5.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.
.....
.....
.....