Loops in C#

Loops in C# with Examples:

In this article, I am going to discuss Loops in C# with Examples. Please read our last article, where we discussed Switch Statements in C# with Examples. In this article, we are going to discuss one of the core concepts of any programming called Loops. Loop Control Statements are very, very important for logical programming. If you are new to programming then please keep in mind that if you understand the working of the loop correctly you could solve most of the problems in the real world.

Loops in C#:

Loops are also called repeating statements or iterative statements. Loops play an important role in programming. The Looping Statements are also called Iteration Statements. So, we can use the word Looping and Iteration and the meanings are the same.

What is looping?

Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly while some condition evaluates to true.

The process of repeatedly executing a statement or group of statements until the condition is satisfied is called looping. In this case, when the condition becomes false the execution of the loops terminates. The way it repeats the execution of the statements or instructions will form a circle that’s why iteration statements are called loops.

So, in simple words, we can say that Loop is nothing but repeating some tasks for some amount of time until the condition is true. There are two types of loops

  1. Counter Loops
  2. Conditional Loops

Before explaining, what are the counter and conditional loops let’s make you understand where we see loops in reality with real-time examples.

Loops Exist in our Daily Life.

Every day I woke up at 6 ->go jogging ->come home->take a bath->had breakfast-> went to college/office-> worked/learn->come back at 6-> watched tv/mobile->had dinner -> went to sleep this routine is repeated every day without change and this we call it has loops in programming.

Here when you wake up tomorrow you will do the same thing and this continues until you are alive. So here condition to break the loop is you have to die. Now let us explain what is the counter loop and conditional Loop.

  1. Counter Loops are the loops, which execute a specific set of instructions a certain number of times. Example: Token system followed in hospitals where the whole intention could be getting the headcount of patients.
  2. Conditional Loops are the loops, which execute a specific task until the condition is true. Example: Attend the online classes until the covid-19 situation comes to control.
Why do we need looping?

The basic purpose of the loop is code repetition. So, whenever the repetitions are required, then in place of writing the statements, again and again, we need to go for looping.

The whole intention of using loops in programming is to make the developer’s job easy and make the code look clean and efficient. The developer goes for loops whenever he wants to execute some instructions a certain number of times. To give you a better understanding of the importance of loops in programming let us write a code without loops and with loops.

Example to print numbers from 1 to 10 without using the loop in C#

Till now what we learned using those concepts If I write a program to print 1 to 10 it looks something like this.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("1");
            Console.WriteLine("2");
            Console.WriteLine("3");
            Console.WriteLine("4");
            Console.WriteLine("5");
            Console.WriteLine("6");
            Console.WriteLine("7");
            Console.WriteLine("8");
            Console.WriteLine("9");
            Console.WriteLine("10");

            Console.ReadKey();
        }
    }
}
Output:

Example to print numbers from 1 to 10 without using the loop in C#

Note: Even though we are able to print the numbers from 1 to 10, the code doesn’t look good as the same instruction is written multiple times also what is it if want to print from 1 to 1000? Or from 1 to 100000? So, without loops, the code not even looks understandable and efficient.

Program to Print 1 to N with a loop in C#
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            for(int i=1; i <=10; i++)
            {
                Console.WriteLine(i);
            }
            
            Console.ReadKey();
        }
    }
}
Output:

The above for loop is an example of a counter loop where the loop runs a specific number of times. Syntax and other things will be discussed in our next article. The above code looks simple and readable. In addition, if I want to print from 1 to 1000 just, I need to change i<=10 to i<=1000 that’s it. So, code can be easily maintainable.

Types of Loops in C#

Iteration statements create loops in the program. It repeats the same code several times until a specified condition is satisfied. Iteration statements execute the same set of instructions until a termination condition is met. There are four types of looping statements in C#. They are as follows:

  1. For loop
  2. For Each Loop
  3. While loop
  4. Do while loop

In this article, I will give you an introduction to the loops, and also, we will be explaining these loops. Let’s first understand the flowchart.

Flowchart of Loop:

Let us understand the flowchart of the loop step by step for a better understanding.

Step1:

This is the starting point of the flowchart.

Loops in C# with Examples

Step2:

Here we are taking the input from the user, whatever the problem is, and some input it is taking.

Loops in C#

Step3:

It is processing the input.

Loops in C# with Examples

Step4:

Flowchart of Loops in C#

As the input is processed then it checks for the condition, if the condition is true then again it goes back and processing will do and then again check for the condition, if the condition is true then again goes back, and so on.

This will be repeated. So, this processing part will go on repeating as long as that condition is true and once the conditions become false it will come out from here and print the output.

Step5:

Flowchart of Loops

Here our flowchart is finished. So, in any procedure, if we have to repeatedly execute some set of statements then we can repeatedly execute them using the loop. So, a loop is used for repeatedly executing some set of statements.

Realtime Example:

This type of thing we do commonly in our daily life repeatedly. We perform some steps like you have a coffee and you have to add some sugar in that. So, you’ll put some sugar and check it. If it’s not sweet yet then we will put some more sugar and check again. If it is sufficiently sweet then you will stop adding the sugar. So, this is a repeating procedure.

Let us take one more example. You are walking towards your home. If you have not reached home then take a step walk and then walk and check, have you reached home? No, then take one or more steps and check again. If yes, stop walking, and if no, you will be going on taking steps.

One more thing, we have seen in the number system like converting a decimal number to a binary number, we will divide that number by two and keep dividing until it becomes zero. We solve these problems which have repeating steps using these different loops:

  1. while
  2. do-while
  3. for
  4. for each
Loops are mainly divided into two categories:
  1. Entry Controlled Loops: The loops in which the condition to be tested is present at beginning of the loop body are known as Entry Controlled Loops. Examples of Entry Controlled Loops are while loop and for loop.
  2. Exit Controlled Loops: The loops in which the testing condition is present at the end of the loop body are termed Exit Controlled Loops. An example of Exit Controlled Loop is the do-while loop. In Exit Controlled Loops, the loop body will be evaluated at least one time as the testing condition is present at the end of the loop body.

In the next article, I am going to discuss While Loop in C# Language with examples. Here, in this article, I try to explain the Loop in C# Language. I hope you enjoy this Loop in C# Language article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.