• Home
  • For, While and Do While Loops

For, While and Do While Loops

Agenda

C# Loops

There may be a situation when user need to execute a block of code several number of times until some condition is met. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Loop statements are used for repetitive execution.

There are primary three types of loops in C#:

C# For Loop

Syntax:

 for (initialization; condition; increment/decrement iterator ){
Statement(s)
}

Example:

Print 0 to 5 Numbers for(int i=0; i<=5; i++){ Console.WriteLine(i); }

While Loops

A while loop statement in C# programming language repeatedly executes a target statement as long as a given condition is true.

Syntax:

Initialization; 
while (Condition){
Statement(s);
increment/decrement;
}

While Loops

Syntax:

Initialization;
do
{
Statement(s);
increment/decrement;
} while (Condition);

      for (int i = 0; i <= 5; i++){  Console.WriteLine(i); } { for (int i = 20; i >= 10; i--) { if ((i != 15) && (i != 13)) { Console.WriteLine(i); } } for (int i=1; i<=4; i++) { for (int j=1;j<=4;j++){         Console.WriteLine(i+" "+j); } } int i = 1; ; while (i <= 5) { Console.WriteLine(i); i++; } int i = 1; while (i <= 5) { if (i != 2) { Console.WriteLine(i); } i++; } int i = 8; do { Console.WriteLine(i); i++; } while (i <= 12); int i = 20; do { if ((i != 18) && (i != 16)) { Console.WriteLine(i); } i--; } while (i >= 15);