System ProgrammingLearn about different types of Loops in C# Programming

Learn about different types of Loops in C# Programming

Another means to control the flow of code execution in a program: Loops.
Loops refer to instructing the application to execute a statement or a block of code repeatedly. The execution will continue either a specific number of times, till a condition is satisfied, or indefinitely.

The for loop
Let’s say you want to print all odd numbers from 1 till 20. To achieve this, you could use a loop like the following:

for (int i=1; i<= 20; i = i + 2)
{
	Console.WriteLine(i);
}

Running this code will give you the following output:

1
3
5
7
9
11
13
15
17
19

You have just written your first loop. This is called a for loop. A for loop is one that will run for a specific number of times. Examine the first line: you instruct the program that you’ll use a for loop by writing for followed by a condition. The condition states that an integer i will start at value 1, cannot be more than 20, and will increment by 2 each round. Then you write the code the will be executed each round. The code simply prints out the value of i. So in the first round (also called iteration) the value was 1, which is the original value we set. Then it was incremented by 2 in the second iteration. It continues this pattern until it reaches the point when i reaches 20. Obviously 20 + 2 = 22, which is more than 20, the condition we set. Accordingly, the loop exits.

The for loop is the best choice when the number of iterations (repetitions) is known in advance.

The do loop
This loop executes code based on a condition. It differs from the for loop in that it is not bound by a number of times. It will go on and on until the exit condition is met no matter how long that takes. So if we want to rewrite our previous example using the do loop. It would be as follows:

int i = 1;
do 
{
    Console.WriteLine(i);
    i = i + 2;
} 
while (i <= 20);

Nothing is too different here. We assigned i the value of 1 to give the loop a starting point. Then you start the loop by typing do to instruct the program that you are going to use a do loop. You write the code that will print the value of i. Then, most importantly, you take care of changing the value of i so that the loop keeps going. Finally, you define the condition when the loop has to exit: when the value of i exceeds 20. This code will give you the exact same output as the previous one.

Note that the body of the do loop will always execute at least once (even if the condition fails at its first check)

The while loop
It’s very similar to the do loop, with one notable difference: the condition is set at the start of the loop rather than at the end of it. That is, in the do loop you are sure that the code will execute at least once before the exit condition it met (the specified condition fails). In the while loop, the code will continue to execute as long as the specified condition is met. Consider the following code:

int i = 1;
while (i <= 20)
{
    Console.WriteLine(i);
    i = i + 2;
}

As you can see, the condition is set at the start of the loop rather than after the code finishes execution.

Which one to use and when?
Well, that depends on what you are trying to accomplish. For example, if you grabbed 10 rows from a database table and you want to loop over them, it will be better to use the for loop because the number of items on which you will iterate is known. But if you are connecting to Twitter for example, and you want to display all tweets related to a specific hashtag, you cannot use a for loop here as you will never know the number of tweets that will be flowing containing your target hashtag. In such a case, a do or a while loop will be your best choice.

Choosing over do or while loops, again, depends on your need. As mentioned, the do loop will allow the code to execute once at a minimum although the exit condition has been met, because the condition is examined after code execution. A while loop does not offer this as the condition is examined before code execution.

Learn Cloud Computing from Scratch for Beginners

Controlling loops
Sometimes you may find yourself in a situation when you want to cancel a loop before the exit condition is met. For example, may be you want to print odd numbers from 1 to 20, but you don’t want to print the number 5 for some reason. C# offers you two keywords to interrupt loops: break and continue. The break command will cause the loop to stop execution of the current iteration and exit. While the continue keyword will make the loop bypass the current iteration only. Loop execution is continued from the start of the next iteration.  Let’s consider both cases in the following examples:

int i = 1;
while (i <= 20)
{
    i = i + 2;
    if (i == 5)
        continue;
    Console.WriteLine(i);
}

The above code will print all the odd numbers from 1 to 20 except the number 5. Notice the if statement we put at the start of the loop code; if i reaches the value 5 do not complete code execution and return to the start of the next iteration. Now examine the following code:

int i = 1;
while (i <= 20)
{
    i = i + 2;
    if (i == 5)
        break;
    Console.WriteLine(i);
}

As you guessed, this code will print the number 3 and stop. We replaced the keyword continue with the keyword break. The later will instruct the loop not only to stop execution of the current iteration, but also to exist the entire loop operation.

Conclusion
In this article, we have discussed Loops with their three forms: the for, the do, and the while. We examined the syntax of each of them and also when and where it is advisable to use each of them.

I hope you enjoyed this article. In the next one, we will revisit variables; you’ll know how to convert variables to different types. We will start discussing new types like enum and struct.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -