LOOPING STATEMENTS
IN C#
Marie Khadija Xynefida P. Ontiveros, DIT
Assistant Professor III
C# WHILE LOOP
The while loop loops
through a block of code
as long as a specified
condition is True:
C# WHILE LOOP
In the example, the code in
the loop will run, over and
over again, as long as a
variable (i) is less than 5:
C# DO/WHILE LOOP
The do/while loop is a
variant of the while loop.
This loop will execute the
code block once, before
checking if the condition is
true, then it will repeat the
loop as long as the condition
is true.
C# DO/WHILE LOOP
The example uses
a do/while loop. The loop will
always be executed at least once,
even if the condition is false,
because the code block is
executed before the condition is
tested:
C# FOR LOOP
When you know exactly
how many times you want
to loop through a block of
code, use the for loop
instead of a while loop:
Statement 1 is executed (one time) before the
execution of the code block.
Statement 2 defines the condition for executing
the code block.
Statement 3 is executed (every time) after the
code block has been executed.
C# FOR LOOP
The example will print the
numbers 0 to 4:
C# NESTED LOOPS
It is also possible to place
a loop inside another
loop. This is called
a nested loop.
The "inner loop" will be
executed one time for
each iteration of the
"outer loop":
C# FOR EACH
LOOPS
There is also
a foreach loop, which is
used exclusively to loop
through elements in
an array:
C# FOR EACH
LOOPS
The following example outputs
all elements in the cars array,
using a foreach loop:
C# ARRAYS
Arrays are used to store multiple
values in a single variable,
instead of declaring separate
variables for each value.
To declare an array, define the
variable type with square
brackets: