|
Loops in C#
|
Loops are generally used to execute repetitive statements. The following are the different types of loops we have in C#
- for loop
- while loop
- Do..While loop
- foreach loop
|
Below is a simple example illustrating for loop.
This sample program expects an integer limit from the user upto which to generate
even numbers. The entered value must be an integer. If the user inputs anything
apart from numbers an exception will be raised and an error message will be shown
to the user. For catching exceptions and showing valid error messages we are using
exception handling in our program using try..catch statements. We will talk about
exception handling in our later article.
|
|
using
System;
class
ForLoopDemo
{
public
static void Main()
{
int Limit=0;
Console.WriteLine("Enter the limit upto which to
generate even numbers?");
try
{
Limit
= Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Entered
value should be a number between 1 and 100000");
}
for (int i = 0; i <= Limit; i++)
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
}
}
}
|
The for loop in the above program has three parts as shown below
for ( <initialization list>; <boolean
condition>; <repetitive list> )
{
<statements>
}
|
The initialization list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter.
Once the initialization list has been evaluated, the for loop gives control to its second section, the boolean condition. There is only one boolean condition, but it can be as complicated as you like as long as the result evaluates to a boolean true or false. The boolean condition is commonly used to verify the status of a counter variable.
When the boolean condition evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the repetitive list, which is normally used to increment or decrement a counter.
|
Understanding while loop
A while loop is very much similar to a for loop except that initialization, checking the boolean condition and incrementing the counter value is done at different steps as shown in the below example, otherwise while loop is same as the for loop.
Note: An important point to keep in mind is that, if you miss incrementing the counter variable, the program will run into an infinite loop.
|
|
using
System;
class
WhileLoopDemo
{
public
static void Main()
{
int Limit=0;
Console.WriteLine("Enter the limit upto which to
generate even numbers?");
try
{
Limit
= Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Entered
value should be a number between 1 and 100000");
}
int i = 0;
// Initialize counter
variable
while (i <= Limit)
// Condition check
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
i++; //Increment the counter
}
}
}
|
Understanding do..while loop |
|
Do..while loop is very similar to while loop except that the boolean condition is
checked at the end of the loop. This means that a Do..while loop is guranteed to
execute atleast once. The same example we have been following thru this article
is rewritten using Do..while loop as shown below. |
|
using
System;
class
DoWhileLoopDemo
{
public
static void Main()
{
int Limit=0;
Console.WriteLine("Enter the limit upto which to
generate even numbers?");
try
{
Limit
= Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Entered
value should be a number between 1 and 100000");
}
int i = 0;
// Initialize counter variable
do
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
i++; //Increment the counter
}
while (i <= Limit); // Condition check
}
}
|
Understanding foreach loop |
forech loop is a new introduction in C#. foreach loop is basically used to loop thru a collection of items in a list or a collection. For example if we have a string array of names and if we want to loop thru the array and print all the names in the array we can use the foreach loop.
To achieve this we can use a for loop as well. But to use a for loop, we need to know how many elements are present in the collection before hand so we can loop that many times and print out the names. What if we dont have the information about number of elements in the collection before hand. Thats when foreach loop becomes very handy.
foreach loop is extremely useful when we donot know how many elements are present in the collection. The below example loops thru the list of names in the Names array and print them to the screen.
|
|
using
System;
class
ForEachLoopDemo
{
public
static void Main()
{
string[] Names = { "Prasad","Giri","Kiran","Ravi"};
foreach (string s
in Names)
{
Console.WriteLine(s);
}
}
}
|
Understanding the significance of "break" and "continue" statements in loops |
continue and break statements can be optionally used to control how the loops are
executed. In general when a continue
statement is encountered, the program will
skip executing the lines following the continue statement and the control will be
transfered back to the first line in the loop and will continue executing.
If a break statement is encountered the control comes out of the loop. Our example
below will print even numbers between 1 and 20.
- The program will print even numbers 1 thru 10.
- After print 10, user is provided with an option to continue printing even numbers or break out of the for loop.
- If user opts B to break out of the loop, the rest of the even numbers are not printed and the execution of the for loop is terminated. So when ever a break statement is encountered in a loop, the program execution breaks out of the loop.
- If user opts C to continue, rest of the even numbers 11 thru 20 are printed. However, an interesting thing to ote is, the line after the continue statement is not executed. This is bcos continue statement will skip the lines following it and control will be transfered back to the first statement in the loop.
|
|
using
System;
class
ForEachLoopDemo
{
public
static void Main()
{
Console.WriteLine("This program will print even
numbers between 0 and 20");
for (int i = 0; i <= 20; i++)
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
if (i == 11)
{
Console.WriteLine("Select
an option B - Break, C - Continue");
string option =
Console.ReadLine();
if (option == "B")
{
Console.WriteLine("You have chosen to break out of the for block and stop printing");
Console.WriteLine("");
Console.WriteLine("This program will terminate now");
break;
}
if (option == "C")
{
Console.WriteLine("Program will continue printing even numbers from 11 to 20");
continue;
Console.WriteLine("This statement will not be printed");
//continue statement will
}
//skip this statement and
}
//continue executing from
}
//the first line of the loop
}
}
|
Njoy Programming
ByPrasad Cherukuri
|