Free Web Development Online Tutorials, Learn to Code
Learn C# Loops, Write for loop in C#, foreach loop, while, do while loop in C# Programming

Loops in C# Tutorial


C# loops example

From the word Loop you can understand a control structure that will help to execute any code multiple times, in some cases you may know how many times the same code to be executed, and sometimes you may know the number at runtimes

In real time C# .Net application development you may come across many such situation where you need to write a loop

There are four type of loops in C#

for loop example in C#

For loop is simple, when you know how many times some code block to be executed there you write for loop, for example if you know your code blook to be excuted for 10 times

for (int i = 1; i <= 10; i++)            
{
                 
    /* here you write code to be executed */
}

foreach loop example in C#

Foreach loop is often used to run loop through a object list collection, in below example we don’t know how many blog we have in the list.

foreach (blogObj b in blogList)
{
                
    /* for example here you write code to display any property of each blog */
                
}

while loop example in C#

while loop includes a Boolean expression as a condition, which returns true or false. It executes the code block, as long as the specified conditional expression returns true.

While(boolean expression)
{
//execute code as long as condition returns true
}
int i = 0;
while (i < 5)
{
    Console.WriteLine("Value of i: {0}", i);
    i++;
}

do while loop example in C#

do-while loop is the same as a 'while' loop, but there while clause is at the end, when condition satisfied, then it exit the loop

do
{
//execute code block } while(boolean expression);
int i = 0;
do
{
Console.WriteLine("print the value of i: {0}", i);
i++;
} while (i < 5);

Note: if you want to come out of the loop for any addition exception condition use keyword break

Nested loop in c#

Sometimes you may need to write a loop inside a loop, which is known as Nested loop in c#.

Think of situation where you need to loop through list collection and each object contain a list of images, so you have to loop through files.

foreach (blogObj b in blogList)
{                
    foreach(image in blogObj.Images)
        {
            // capture each image info.
        }
                
}

c# loop through array

You can loop through any type of array object, that can be simple string array or files in folder

//Loop through string array
string[] animals  = { "tiger", "bird", "cat", "dog" };
foreach (string s in animals)
{                
        Console.WriteLine(s);
                
}
//loop through files in folder
// or file collection
File[] files = MyFolder.GetFiles();
foreach (File f in files)
{                
       
    // f contain each file object
     Console.WriteLine(f.Name);
                
}
Comment
Name
Email
Website
Subscribe