C# Iteration

C# Code Snippets Iteration


In this code snippet, we’ll find out how to iterate with the for, foreach, while and do while loop. 

What loops do is execute the code in their curly brackets(multiple times, maybe only once or even never). The number of times that they will do that depends on the condition that will get evaluated at the beginning of each iteration. Usually, the condition consists of the maximum number of iterations and the counter variable which contains the number of iterations so far. The counter is an integer that gets increased at the end of the loop. This way we can keep track of how many iterations were performed. 

But the loop condition doesn’t always have to be implemented like that. The condition is basically an if the statement. If it evaluates to true the loop will keep loping if it evaluates to false the loop will stop. So, you can stick in anything that will evaluate to true or false. Or an actual variable holding a value of true or false.  

These are the basics of how a loop works. But as you will see in the code example below there are some differences between these loops. Let’s check out what the differences are and how to implement each loop.


using System;

namespace Iteration
    class Program
        static void Main(string[] args)

            //For loop.
            Console.WriteLine("Iterating with the for loop.");

            //Here i will be the counter. 
            //First it gets declared, then we check if it's bigger than 5.
            //The code in the curly brackets gets executed if the check evaluated to true.
            //And at the end i gets increased by one. 
            for (int i = 0; i < 5; i++)


            //While loop.
            Console.WriteLine("Iterating with the while loop.");

            int j = 0;

            while (j < 5)


            //Do while loop.
            //Always executes at least once. 
            Console.WriteLine("Iterating with the do while loop.");

            int k = 0;

            } while (k < 5);


            //Foreach loop.
            //It executes once fore everya item in array or collection.
            Console.WriteLine("Iterating with the foreach loop.");

            int[] intArray = new int[5] { 1, 5, 6, 8, 4 };

            foreach (var item in intArray)


Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger