Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Learn Loops in C# tutorial


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 in C#
  • foreach loop in C#
  • while loop in C#
  • do while loop 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 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
You can write a loop inside a loop if required.

 
Loops in C#
Learn C# Online Tutorial


Group Training