III. Iteration Structure (Loop Structure)
There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages.
III.1-For-Loop Statement
Here, you will learn how to execute a statement or code block multiple times using the for loop, structure of the for loop, nested for loops, and how to exit from the for loop.
The for keyword indicates a loop in C#. The for loop executes a block of statements repeatedly until the specified condition returns false.
III.2- While-Loop Statement
C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns true.
The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false. It executes the code block until the specified conditional expression returns false.
The for loop contains the initialization and increment/decrement parts. When using the while loop, initialization should be done before the loop starts, and increment or decrement steps should be inside the loop.
III.3- Do-While Statement
The do while loop is the same as while loop except that it executes the code block at least once.
The do-while loop starts with the do keyword followed by a code block and a boolean expression with the while keyword. The do while loop stops execution exits when a boolean condition evaluates to false. Because the while(condition) specified at the end of the block, it certainly executes the code block at least once.
Example: do-while Loop
int i = 0;
do
{
Console.WriteLine("i = {0}", i);
i++;
} while (i < 5);
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
Specify initialization out of the loop and increment/decrement counter inside do while loop.
0 Comments