Using while and do-while Loops
Explore how while and do-while loops function in Dart to execute code based on conditions. Learn to use sentinel values for input-driven loops, understand the structural differences, and avoid infinite loops by updating control variables. This lesson helps you write reliable, condition-based repetition in Dart programs.
When we use the word "while" in everyday language, we often relate it to time and ongoing events. For instance, stating that we are reading a book while a sibling gets ready indicates that the act of reading continues as long as the other event is taking place.
A while loop in Dart behaves similarly. It evaluates a boolean condition and repeatedly executes a specific block of code as long as that condition evaluates to true.
The while loop
Before applying the loop to a real scenario, let us understand its structural components.
Structure of the while loop
We construct a while loop using the while keyword, followed by a condition wrapped in parentheses, and finally a block of code enclosed in curly braces.
The program evaluates the condition first. If the condition is true, the program executes the code block and then checks the condition again, repeating this cycle until the condition becomes false.
Let us look at how we can use a runnable while loop to print numbers sequentially from 1 to 10.