Thursday 8 September 2011

Control Statements

C# has statements such as if ….. else ….. and switch…case which help you to
conditionally execute program.C# provides you with various looping statements, such as do… while, while, for and foreach….in.

1. The if ….else….. Statement
Consider a student marks and grade evaluation. For Marks above 75 the grade is ‘A’ and
for below 75 is ‘B’. In this situation when you need to execute some code based on some
condition, you can make use of, if …. else …...
The Cultural syntax normally used is as follows:
if (condition)
{
Executable statements when the condition is True
}
else
{
Executable statements when the Condition is False
}
OR using else if for Advanced Decision making
if (condition)
{
Executable statements
}
else if (condition)
{
Executable statements
}
Single if can have multiple else if with conditions, as mentioned above in else if format.
Nesting if …else Constructs
if (condition)
{
if (condition)
{
Executable statements when the condition2 is TRUE
}
else
{
Executable Statements
}
else
{
Executable statements
}
One important thing to keep in mind when nesting if…else constructs is that you must have remember to close the
brace ({ }) for every brace that you open.

2. The switch…case Statement.
The switch statement is a control statement that handles multiple selections by passing
control to one of the case statements within its body.
The switch…case Statement is similar to if…else. The only difference between two is
that if and else if can evaluate different expressions in each statement, but the switch
statement can evaluate only one expression.
The drawback of if...else construct is that it isn’t capable of handling a decision situation
without a lot of extra work. One such situation is when you have to perform different
actions based on numerous possible values of an expression, not just True or False. For
instance performing actions based on Students Grade.
if ( Grade.Equals (“A”))
{
…….
}
else if (Grade.Equals (“B”))
{
……
}
else if (Grade.Equals (“C”))
{
……
}
else if (Grade.Equals (“D”))
{
……
}
else
{
.….
}

As you see the structure can be a bit hard to read and if the conditions increase you may
end up writing a confusing and an unreadable piece of Code
The switch uses the result of an expression to execute different set of statements.
The syntax for the select…case Statement is as follows:
switch (expression)
{
case constant-expression:
statement
jump-statement
default:
statement
jump-statement]
}
Notice that the jump-statement is required after each block, including the last block
whether it is a case statement or a default statement.
Note: default is used to define the code that executes only when the expression
doesn’t evaluate to any of the values in case Statements .Use of default case is
optional
Let’s see the same example as above but this time with switch case.
switch(grade)
{
case “A”:
Executable statements
jump-statement
case “B”:
Executable statements
jump-statement
case “C”:
Executable statements
jump-statement
case “D”:
Executable statements
jump-statement
default :
Executable statements
jump-statement
}

Branching is performed using jump statements, which cause an immediate transfer of the
program control.(break, continue, default ,goto ,return)
Evaluating More than one possible Value in a case Statement is not possible in C#,
but VB.Net does allow evaluating more than one Value.
 
3. for Statements.
The for loop executes a statement or a block of statements repeatedly until a specified
expression evaluates to false.
for ([initializers]; [expression]; [iterators]) statement
where:
Initializers: A comma separated list of expressions or assignment statements to initialize
the loop counters.
Expression : expression is used to test the loop-termination criteria.
Iterators : Expression statement(s) to increment or decrement the loop counters.
Example print numbers from 1 To 100
for (int intctr =1; intctr <= 100; intctr++)
Debug.WriteLine(intctr);
This routine starts a loop with a for statement after a variable intctr is declared. This loop
initializes intctr to 1 and then prints 1 through 100 to the output window.
Note: you can declare variable in the Initialization part of the for loop separated by
comma.
Example : print even number from 1 to 100
for(int i=2; i <= 100; i = i + 2)
Debug.WriteLine(i.ToString());
Example : To Sum the total of all number from 1 to 10
for( i =1 ; i < 11 ; i++)
sum = sum + i ;
Example : The statement below can be used as an infinite loop.
for ( ; ; );
Example of use of for loop.
Let us see how to a write table of 2 using for loop.
for(int j = 1,i = 2; j <= 10; j++)
Debug.WriteLine("2 X " + j.ToString() + " = " + i*j );
Output:
2 X 1 = 2
..
..
..
..
..

2 X 10 = 20
An Example of Nested For loop.
Let us write a small code to display a structure of stars ‘*’ in triangle format.
*
* *
* * *
* * * *
* * * * *
* * * * * *
Let us have a label with name stars. Increase the height of the label to get a clear view of
the image.
string star="";
for(int i = 0; i < 5 ;i++) // First loop to count the rows
{
for (int j = 0; j <= i; j++) // Second loop to count
the columns
{
star = star + " * ";
}
Debug.WriteLine(star);
star = "";
}

Note: For better readability you must always indent your
Codes.
 
4. foreach…in Statement
The foreach…in Statement is used to repeat a set of statements for each element in an
array or collection.
The foreach…in statement is executed if there is at least one item in an array of
collection. The Loop repeats of each element in an array or collection.
The syntax for the foreach…in statement as follows:
foreach (type Component in Set )
{
Executable statements
}
Component is the variable used to refer to the elements of an array or a collection.
Set refers to an array or any collection object.
e.g.
string[] weeks = {"Monday", "Tuesday", "Wednesday",
"Thursday",
"Friday", "Saturday", "Sunday"};
foreach(string eachday in weeks)
{
MessageBox.Show(eachday);
}

An example for using foreach element in a collection of string into a single string
element.
Each element of array which is of type string is read from the collection and stored into
the single string type object.
 
5. while…Statement
The while… Statement is used to repeat set of executable statements as long as the
condition is true.
The syntax for the while… statement is as follows:
while (Condition)
{
Executable Statements
}
In this if the condition is satisfied then the statements are executed. Else it will not enter
the while condition at all.
example of infinite loop is
while (true);
Example print numbers from 1 to 100
int i = 1;
while ( i <= 100)
{
Debug.WriteLine(i.ToString());
i++;
}
Example print even numbers from 1 to 100
Int i = 2;
While( i <=100)
{
Debug.WriteLine(i.ToString());
i = i + 2;
}
 

6. do...while Statement
The do...while Statement is similar to while… Statement.
do
{
Statements to Execute
}
while (condition)
example print numbers from 1 to 100
int i = 1;
do
{
Debug.WriteLine(i.ToString());
i++;
}while( i <= 100);
example print even numbers from 1 to 100
int i = 2;
do
{
Debug.WriteLine(i.ToString());
i = i + 2;
}while( i <= 100);
A Complete Example with set of control statements.
We will create a C# application, which will accept students name and its grade.
Depending upon the type of grade it will add remarks.
int value=0, ctr=0;
//Accept a number from the user
Console.Write("Enter the number of students : ");
value = Int32.Parse(Console.ReadLine());
string [] arrName= new string[value];
string sGrade ="";
string [] arrRemarks= new string[value];
while (ctr < value)
{
//Accept the name of the students
Console.Write("Enter the name of the Student" + (ctr +
1) + " : ");
arrName[ctr] = Console.ReadLine();
//Accept the grade of the Student
Console.Write("Enter the grade of the student
A/B/C/D/F : " );
sGrade = Console.ReadLine();
// Assign remarks to students
switch (sGrade.ToUpper())
{
case "A":
arrRemarks[ctr] = "Excellent";
break;
case "B":
arrRemarks[ctr] = "Good";
break;
case "C":
arrRemarks[ctr] = "Fair";
break;
case "D":
arrRemarks[ctr] = "Poor";
break;
case "F":
arrRemarks[ctr] = "Fail";
break;
default:
Console.WriteLine("Incorrect value entered
");
return; // To come out of the program
}
ctr = ctr + 1;
}
// Display the summary on the Console
for (ctr = 0 ;ctr< value; ctr=ctr+1)
{
if (arrRemarks[ctr].Equals("fail"))
{
Console.WriteLine(arrName[ctr] + " has failed in_
exams ");
}
else
{
Console.WriteLine(arrName[ctr] + "'s
performance is " + arrRemarks[ctr]);
}
}

No comments:

Post a Comment