C# Simplified, part 2: Methods & Programming Constructs - Different types of looping statements in C#
(Page 5 of 6 )
In the previous session, you have learned about decision making statements such as if-else and switch-case. C# offers a set of looping constructs with which you can perform certain tasks such as the printing of numbers from 1 to 30, or printing only the even/odd numbers. There are basically three types of looping constructs. For, while and do-while are explained in detail below.
for Loop
This loop is used to iterate a value for a fixed number of times. You should be very careful while using this loop, as incorrect usage might result in an infinite loop and crash the application. Its usage is given below:
Usage
for(Initial Value, Condition, Increment/Decrement)
{
Statements
}
The increment and decrement operators can be specified using either the ++ or - operators. In listing 2.11, a loop is created which will print numbers from 1 to 10. Since I have applied the <= operator, the number 10 will also be printed. If you apply the < operator, only 9 will be printed.
Listing 2.11
using System;
class ForLoop
{
public static void Main()
{
for(int I = 1; I<=10;I++)
{
Console.WriteLine(I);
}
}
}
while Loop
This looping construct is very similar to the for construct discussed above. The only exception is that the condition is specified first, and the loop will continue to execute as long as a particular condition is true. Its usage is shown below:
Usage
while(Condition)
{
Statements
}
If the specified condition is false, the statements within the loop won't execute. Listing 2.12 is a modified version of listing 2.11. But the resulting output will be different, as numbers from 2 to 11 will be printed. Here you have to declare the variable and increment/decrement operators separately, as shown in listing 2.12.
Listing 2.12
using System;
class WhileLoop
{
public static void Main()
{
int I = 1;
while(I <=10)
{
I++;
console.WriteLine(I);
}
}
}
do-while Loop
This looping construct is also similar to that of the while loop, but the condition is specified last, and after closing the do construct. Its usage is given below:
Usage
Do
{
Statements
}
while(Condition)
As explained above, the condition is tested at the end of the loop. Hence, the statements within the loop are executed at least once even if the condition is false. In listing 2.13, numbers from 1 to 11 will be printed. If you change the condition to greater than, then the loop will execute once.
Listing 2.13
using System;
class DoWhileLoop
{
public static void Main()
{
int I = 0;
do
{
I++;
Console.WriteLine(I);
}
while(I<=10);
}
}
Next: break Statement >>
More C# Articles
More By Anand Narayanaswamy