Fiveable
Fiveable

while loop

Definition

A while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.

Analogy

Imagine you're playing a video game and your character needs to keep collecting coins until they reach a certain score. The while loop is like the game's instructions telling your character to keep collecting coins until the score reaches the desired value.

Related terms

Condition: A condition is an expression that evaluates to either true or false, determining whether the code inside the while loop should be executed.

Loop body: The loop body refers to the block of code that gets executed repeatedly as long as the condition in the while loop remains true.

Infinite loop: An infinite loop occurs when the condition in a while loop always evaluates to true, causing the code inside it to repeat indefinitely.

"while loop" appears in:

Practice Questions (8)

  • Which example demonstrates the use of a while loop?
  • How is a for loop different from a while loop?
  • How can a for loop be converted into a while loop?
  • When would you choose a while loop over a for loop?
  • What while loop will give the same output as this for loop: for (int i = 0; i < 10; i++) { System.out.println(i); }
  • What is the advantage of using a for loop over a while loop for array traversal?
  • What is the purpose of a while loop?
  • What happens if the condition of a while loop is always true?


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.