DEV Community

Cover image for 3 Kinds of Loops That We Use All The Time Without Knowing Their Names.
Codeguage
Codeguage

Posted on • Originally published at codeguage.Medium

3 Kinds of Loops That We Use All The Time Without Knowing Their Names.

Loops are an integral part of programming. Without them, we can't even think of the modern era of computing that we all live in today. Seriously!

They are the heart of computer automation that help us automate a lot of stuff quite nicely and intuitively.

As far as writing loops is concerned, there are three extremely common types of loops that we use in many programs, often without being aware of the exact kind of loop that we're using.

Those three types are as follows:

  • Counter-based loops
  • Input-validation loops
  • Sentinel-controlled loops

Let's explore each one of these, in detail.


Counter-based loops

As the name suggests, counter-based loops are loops that are based on a counter. A counter is simply a variable to help keep track of incremental (or decremental) numbers.

The most typical example of a counter-based loop is a for loop to iterate over all the elements of a given array.

In such a loop, the counter is typically taken to be i, beginning at 0, ending at the index of the last element in the array, and incrementing by 1 with each subsequent iteration.

Below is an example of a counter-based loop:

var nums = [1, 2, 3];
// Counter-based loop.
for (var i = 0; i < nums.length; i++) {
   console.log(nums[i]);
}
Enter fullscreen mode Exit fullscreen mode

A counter-based loop doesn't always have to increment. It can even decrement, as shown below:

var nums = [1, 2, 3];
// Decrementing counter-based loop.
for (var i = nums.length - 1; i !== 0; i--) {
   console.log(nums[i]);
}
Enter fullscreen mode Exit fullscreen mode

Time to move to the next type, i.e. input-validation loops.


Input validation loops

Input validation loops are meant to keep running unless a given piece of input is valid.

They are typically powered by a while loop, since the number of iterations after which the given input will become valid is unknown, and iterating an unknown number of times is what while should be used for.

Input validation loops are common when developing CLI programs where input is routinely obtained from the user.

Below is an example of an input validation loop in JavaScript that is meant to let only numeric inputs pass through it:

var input = Number(prompt('Enter a number'));
while (isNaN(input)) {
   alert('Invalid input.')
   input = Number(prompt('Enter a number'));
}
console.log('The number is:', input);
Enter fullscreen mode Exit fullscreen mode

Sentinel-controlled loops

A sentinel-controlled loop is one where the execution continues as long as the entered value is not a given sentinel.

A sentinel is simply a special value that's there for a special purpose.

For instance, suppose that a program asks the user to input a list of positive numbers to add. A sensible sentinel value could be -1 — the input of this value would signal the end of the list of numbers.

Sentinel-controlled loops are also extremely common in CLI programs.

Remember the idea of entering quit or exit in a CLI application to exit the window? This is an instance of a sentinel-controlled loop that runs until we enter the value quit or exit as input.

Below is an illustration of a sentinel-controlled loop in JavaScript that's meant to end when the given input is -1:

var sum = 0;
var input = prompt('Enter a number, -1 to exit.');
while (input !== '-1') {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}
alert(`The sum is ${sum}.`);
Enter fullscreen mode Exit fullscreen mode

In the end…

Loops are of immense importance in the world of computing. Likewise, needless to say, all programmers must perfect them to the core.

To explore more details about working with loops in JavaScript, refer to the following chapters in our comprehensive JavaScript course:

Once you're done learning the bits and pieces of these simple loops, there are even some exercises to try out:

  1. Multiply All
  2. Greatest Common Divisor
  3. Selection Sort
  4. Collatz Conjecture

Top comments (0)