credits to intully

While Loops Explained

Robert Long
2 min readSep 1, 2020

--

The while loop is a simple control structure that allows a body of code to be repeated when the condition is true. It can emulate both the for loop and the for each loop. There are situations where the while loop is all you need.

But REALLY, are while loops still used these days? YES, they are! Here are some scenarios where while loops are the most appropriate control structure:

  • Indefinite Conditions — these include console menu selections, mutex locking, event-driven scenarios (UI thread keeping application running, embedded systems to scan for interrupts, and even architectural using in NodeJS) can all be done simply with the while loop
  • Dealing With Iterators — collections, especially ones supported natively by frameworks in languages C#, Java, C++, and Python heavily utilize iterators. With While loops, you can grab the container and call hasNext followed by next to iterate through the entire collection. These collections come in the form of arrays, linked/array lists, data/network streams, and even when dealing data coming back from databases all love to use iterators.

For instance, say you have an console application that writes to your journal entry every day. The menu option has 1. Write a New Entry, 2. View a Past Entry, and 3. Exit Application.

It is made up of 2 main elements:

  • Condition — when the condition is true, execute the body of the loop
  • Body — the scope that contains the procedures to run when the condition passes the check

--

--