Looping Techniques: Ali Shakir Alahmed
Looping Techniques: Ali Shakir Alahmed
Looping Techniques
2022 –
2023
Looping or Iteration in C#
while
do…while
2
while statement
while
(condition)
statement;
3
Display 1 to 5 on screen
static void Main() {
int i;
i = 1;
while (i <= 5) { while version
Console.WriteLine(“{0}”, i);
i++;
}
}
while ( ??????
N > 0 )
{
FACT = ??????
FACT * N ;
????
N-- ;
};
Console.WriteLine(”The factorial is {0}.”,FACT);
} 7
Control Loops: example
static void Main() {
int N, SUM=0;
while (N != -1) {
SUM = SUM+N;
Console.Write(”Enter number or -1 to
quit”);
N = int.Parse(Console.ReadLine());
9
Nested while Statements Example:
Output:
Line 1 : 0123456789
Line 2 : 0123456789
Line 3 : 0123456789
do…while statement
For Single Statement do {
statement;
} while
(condition);
For Multiple Statements
do
{
statement-1;
statement-2;
.
statement-N;
} while
(condition); 11
do…while statement
Do while :
int i = 1;
do
{
Console.WriteLine(i);
i++;
}
while (i <= 10);
Nested do while Statements Example:
int i = 1;
do
{
Console.WriteLine("line=" + i);
int j = 0;
do
{
Console.WriteLine(j);
j++; Output:
} Line 1 : 0123456789
while (j < 10); Line 2 : 0123456789
Line 3 : 0123456789
i++;
}
while (i < 4);
Console.ReadKey();
Control Loops: example
static void Main() {
int N, SUM=0;
do
{
Console.Write(”Enter number or -1 to quit”);
N = int.Parse(Console.ReadLine());
SUM = SUM+N;
} while (N != -1);
14