Conditional Looping Statements in C#.NET

 

Conditional Looping Statements

C# provides 4 loops that allow you to execute a block of code repeatedly until a certain condition is met; They are:

·       for

·       while

·       do while

·       foreach

 

For Loop

For Loop is a loop in programming languages like C# that repeats a block of statements until a condition provided is satisfied. Unlike other less structured loops like while and do. While, this loop contains initialization, condition and increment/decrement before the loop statement.

syntax:

for (initialization; condition; increment/decrement)

{

    statements;

}

            Example

The below statement will execute 4 times repeatedly until the specified condition gets fail.

            for(int i=0; i<4; i++)

            {

            Console.WriteLine(‘Hi’);

            }

 

While

While Loop is a loop in programming languages like C# that repeats a block of statements until a given condition is true. The condition comes after while and it can be any expression that return Boolean value. The expression inside the while loop is executed only if the condition is satisfied. 

Syntax:

while (condition)

{

    statements;

} 

Example:

            Int i = 0;

            While(i<4)

{

                        Console.WriteLine(‘Hi’);

}

Do While

Do While Loop is just like any other loop in C#, but in this loop we have condition at the end of the loop. So this guarantees the execution of statements inside the loop at least once and the loop will be repeated if the condition is satisfied until the condition is false. The condition can be changed in the loop statements.

Syn:

do

{

   <statements>;

 

} while (condition);

Example:

Int i=0;

do

{

Console.WriteLine(‘Hi’);

}while(i<4);

 

Foreach

foreach loop is extension of For Loop. This loop executes block of statements for each member of an array. Indexes of elements are not needed for this loop, just the current element of array is available inside the loop.

Syn:

foreach (datatype  variable_name  in  array_list)

{

    <statements>;

}

 

Here, datatype indicates the data type of the elements of the array. variable name is the name for variable where elements of array will be stored.

in is a keyword that points to the array and array name is the name of array

 

Example:

char[] ovels={‘a’ ,’e’, ’I’, ’o’, ’u’};

 

foreach(char ch in ovels)

{

Console.WriteLine(ch);

}

Comments

Popular posts from this blog

Email Sending through O365 using OAuth Protocol

IISRESET vs App Pool Recycling ?

Deploy .Net6.0 Web api with docker