What Are Loops In Software Development?

What Are Loops In Software Development?

ยท

8 min read

Most of what we do in life are mundane things. These boring chores are a necessity and we wouldn't be able to function as people without them. Whether it's waiting for the traffic light to turn green or our daily preparations for work, we humans have a lot of repetitive tasks that we just can't avoid if we're to achieve anything worthwhile daily.

Luckily, due to software development, we can now automate some of our most boring chores, like doing the laundry, driving, cooking (some meals), etc. Machines are capable of reliably carrying out repetitive tasks and delivering the same outcome regardless of whether it's the first time they're repeating the task or the one-millionth time. On the other hand, we humans get bored to tears and our emotions can affect the quality of the outcome of our repetitive tasks ๐Ÿ˜….

A loop GIF.gif

Introducing Loops

Software developers like my humble self ๐Ÿคง are able to teach machines how to carry out repeated tasks using a programming concept known as loops. Loops, like the name suggests, is code written to carry out repeated functionalities till infinity and beyond in some cases.

Loops are so powerful that it's hard to write an algorithm without leveraging them. It's important to note that loops are as powerful as they are dangerous, and a poorly written loop can exhaust the machine's resources in minutes! You must remember that every instruction given to a machine requires the allocation of processing power and the use of storage memory. A loop can quickly wear a machine thin if the conditions it lives by are too loose.

Basically, there are three types of loops; Do While, For loop, ForEach, and While loops. These three loops encapsulate most of the implementations of loops in software development. With either one of these loops, you can pretty much get a machine to do whatever you want... forever.

An image of a little girl sitting on a man's laps while she's being taught by the man

A Relatable Explanation

A simple example that easily compares the Do While, For, ForEach, and While loop is a situation involving cutleries and a table, A Do While loop will say "Check that table, while there are cutleries on the table, pick them up and paint them", a For loop will say "There are cutleries on the table, paint all the cutlery on that table blue", a ForEach loop can say "Pick all the cutleries on the table and paint them, however, if the cutlery is a fork, please paint it yellow, if it's a spoon, paint it red, and if it's a knife please paint it blue.", and a While loop will say "As long as there are cutleries on the table, pick it up and paint it blue".

An image of a guy about to run while wearing a tracksuit

Do While

Do While loops (also known as While loops) are quite close to For loops, so much so that it's easy to mistake one for the other. The major difference between a Do While loop and a For loop is that a Do While loop will run at least regardless of if the condition that should begin the loop is true or false. The code snippet below should help put things into perspective.

    using System;

namespace DemoApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int sampleValue = 0;
      do 
      {
        Console.Write($"{sampleValue}, ");
        sampleValue++;
      }
      while (sampleValue < 10);
    }
  }
}

The code snippet above can easily be translated to English as "sampleValue is zero, now increase the value by adding one to it, then check if the result is less than ten. As long as the result of sampleValue is less than ten, increase the value by one".

An image of an axe next to split wood

For Loop

Personally, I think every loop is just a slight modification of for loop in the sense that it's possible to write a for loop that performs the same function as these other loops. A for loop is typically divided into three; a declaration of the value that the entire loop is based upon, the condition that the loop evaluates to determine whether or not to run indefinitely, and the instruction that the loop should perform continuously.

The best way to explain this is with the code snippet below

using System;

namespace DemoApplication
{
  class Program
  {
    static void Main(string[] args)
    {
     for (int sampleValue = 0; sampleValue < 10; sampleValue++) 
      {
        Console.Write($"{sampleValue}, ");
      }  

    }
  }
}

To further simplify things, see the first declaration as the foundation of the loop, int sampleValue = 0 is a declaration that must be true for the loop to begin to make sense to the computer, this is why we typically assign values to variables here in order to absolutely guarantee the declaration is true.

The second declaration sampleValue < 10 is more of an instruction to check the value being declared to ensure it's true. This part of the code is extremely crucial as it can make or break the code. It's typically what stops the code from running forever, it's the check and balance for the loop. As long as the declaration here is true, the code will continue to run (under normal circumstances) indefinitely.

The third declaration sampleValue++ is an express order and the machine will carry it out without fail. This order is the looping instruction that the machine will repeat till the second declaration is false. Within the block of code just after this line, any form of instructions can be written in addition and they will also run till the second declaration becomes false.

Summarily the code snippet above can be translated into plain English as "The initial value of variable sampleValue is zero, as long as sampleValue is less than 10, increase the value of sampleValue by one, and write out the values of sampleValue according to the format below".

An image of two women picking rice

ForEach Loop

ForEach loops are picky as they are repetitive, while the For loops can be termed mindless drones in the way they operate, ForEach loop in my opinion is the more intelligent loop as it's precise enough to delve deeper into instructions and execute more bespoke operations on a case-by-case basis.

ForEach loops are used to capture a lot of cases or a group of results yet pick each unit of the group of results and treat them as a standalone unit while applying the predefined instructions on the results (individually).

The code snippet below will give you a frame of reference

using System;

namespace DemoApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] Companies = {"Microsoft", "Netflix", "Amazon", "Alphabet", "Meta", "Starbucks", "McDonalds"};
      foreach (string company in Companies) 
      {
          if((company.ToString().ToLower() == "starbucks") || (company.ToString().ToLower() =="mcdonalds"))
        {
            Console.WriteLine($"{company} is a food giant!");
        }
        else 
        {
            Console.WriteLine($"{company} is Big Tech!");
        }

      }   
    }
  }
}

The above code snippet is a bit easier on the eyes than a For loop ๐Ÿ˜…. A ForEach loop is best suited for working with a group of data, that way it can evaluate individual units of the list, group, or array of the data. The code snippet above can be translated to English as "Here are a box of company names, the company names are in a box called "Companies", please pick out each company name in the box of companies.

Look at each company name and if the company's name in lowercase is either "starbucks" or "mcdonalds", write out the company name and attach the phrase " is a food giant!" to the name, or else attach the phrase " is Big Tech!" to the company name.

An image of horses running in the wild

While Loop

In my opinion, While loop is the most likely to run your system ragged. You have to be careful to ensure the condition behind the loop is tight enough to ensure you don't burn out your system. The While loop will continue to run indefinitely as long as the condition you specified is true, which is why you need to be careful with your condition.

The code snippet of the while loop is probably the easiest to read in my opinion. The sample below should help you gauge it yourself ๐Ÿ˜.

    using System;

namespace DemoApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      int sampleValue = 0;
      while (sampleValue < 10) 
      {
        Console.Write($"{sampleValue},");
        sampleValue++;
      }
    }
  }
}

The code snippet above translates to English as "As long as sampleValue is less than ten, add one to the value".

An image of a girl walking down a dark path, holding on to three balloons that look like planets

Finally

It's important that loops of different types can be used together, we call it "nested loops" when a loop is found inside another loop, it has a lot of performance costs though. Also, it's possible to use conditional statements inside loops. Technically, if you're willing to waste time writing extra lines of code while leveraging conditional statements, it's possible to use a type of loop to do something outside of its predefined functionality in the same way a cutlass can somehow do the job of a hoe ๐Ÿ˜‚. It can be done, but I wouldn't advise it.

It is important to note that despite the fact that loops look like some unstoppable aspect of programming, it is possible to terminate a loop even when all the conditions check out fine. Because loops are resource-intensive at times, the machine monitors them closely and can break the loop in the event that the operation being carried out by the loop is exhausting the computer or bringing up invalid results. For example, pointing to a value that doesn't exist can throw up errors that break the program out of the loop.