C Sharp Loops
In a program
many times you would need to repeat instructions. In C#, the for statement is
one form of a loop that lets you repeat statements. However, as we already
know, a statement can also be a block of statements, thus it also allows
repetition of multiple statements.
For
Loop.
The Basic
Structre of For Loop
for(assignment;
condition; increment/decrement)
{ statements or block of statements}
Example:1
For(i=1;
i<=15; i++)
{
Console.writeline(“The
value of i is {0}”,i)
}
Example:2
class xyz
{
static void Main()
{
int i;
for ( i = 1; i <= 5; i++)
System.Console.WriteLine
("Hi {0}", i);
}
}
Output
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
The for has
2 semicolons as part of its syntax or rules. The statement goes on till the
condition is false. When i has the value 6, the condition checked is, is 6
<= 5. The answer being false, the for terminates. This is how the for
statement enables the repetition of code.
While
Loop.
Note: The
while loop takes a condition before entering the first iteration, hence the
variable i is initialized to 1 before entering the loop.
General Form
of while Loop is
while(expression)
{ statements or block of statements}
Example:1
int i=1;
while(i<=10)
{
Console.writeline(“The
value of i is {0}”,i);
i++;
}
Example:2
class xyz
{
static void Main()
{
int i;
i=1;
while ( i <= 5 )
{
System.Console.WriteLine
("Hi {0}", i);
}
}
}
The
condition checks whether i <= 5 evaluates to true. Currently the value of i
is 1. The condition evaluates to true and the statement within the curly braces
is executed. System.Console.WriteLine is called with Hi and the value of i.
Note that here we are not changing the value of i within the loop. Since the
value of i remains 1 the condition always evaluates to true and the loop will
go on forever, indefinitely.
Our next
program3 will resolve this problem.
Example :3
class xyz
{
static void Main()
{
int i;
i=1;
while ( i <= 5 ){
System.Console.WriteLine
("Hi {0}", i);
i++;
}
}
}
Output
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
This program
is similar to the previous one. The only change that we have made is that we
added the line i++; This will go on until i becomes 6. Once i is 6 the condition
evaluates to false and the loop terminates.
Now the
question is, "Should I use a for or a while?' To answer your question in
the most simple manner is that the for loop is similar to the while loop In
other words, it is at your discretion to use the one you are comfortable with.
Once again C# offers you multiple ways of doing the same thing.
do
while Loop.
Note: The
while loop executes first and , then the Condition is Checked. The loop will
continue while the condition remains true.
General Form
of while Loop is
while(expression)
{ statements or block of statements}
Example:1
int i=1;
do
{
Console.writeline(“The
value of i is {0}”,i);
i++;
} while(i<=10)
Example:2
class xyz
{
static void Main()
{
int i;
i=1;
do
{
System.Console.WriteLine
("Hi {0}", i);
} while ( i <= 5 )
}
}

0 comments: