Breaking News

Control Statement in C#

C# uses two types of control statements:
? Conditional Statements
? Looping
 
Conditional Statements
 
In C#, there are two types of conditional statements:
? if statements
? switch statements
 
if statements
 
The first conditional statement is programmer’s favorite “if” statement. It has three forms:
 
1. Single selection
2. if-then-else selection
3. Nested if-else selection
 
Single if statement
 
The general syntax of single if statement is as below:
 
if (condition)
{
// Body of if block
}
 
IfTest.cs
 
//understanding if statement
using System;
class IfTest 
{
 	public static void Main()
 	{
 		string s;
 		int i;
 		Console.WriteLine("Enter a Number: ");
 		s = Console.ReadLine();
 		i = Int32.Parse(s);
 		//single selection
 		if( i > 0)
 	{
 			Console.WriteLine("The number {0} is positive",i); 			}
 	}
}
 
if – else statements
 
The general syntax of if-else statement is given below:
 
if (condition)
{
	// Body of if block
}
else
{
	// Body of else block
}
 
IfthenElseTest.cs
 
//understanding if-else statement
using System;
class IfthenElseTest 
{
 	public static void Main()
 	{
 		string s;
 		int i;
 		Console.WriteLine("Enter a Number: ");
 		s = Console.ReadLine();
 		i = Int32.Parse(s);
 		//if-then-else selection
 		if(i > 0)
 		{
 			Console.WriteLine("The number {0} is positive",i);
 		}
 		else
 		{
 			Console.WriteLine("The number {0} is not positive",i);
}
 }
}
 
Nested if-else statements
 
The general syntax of nested if-else statement is given below:
 
if(condition)
	{
		// Body of if block
}
else if(condition)
{
	// Body of else if block
}
else
{
	// Body of else block
}
 
NestedIfTest.cs
 
//understanding Nested-if-else statement
using System;
class NestedIfTest 
{
 	public static void Main()
 	{
 		string s;
 		int i;
 		Console.WriteLine("Enter a Number: ");
 		s = Console.ReadLine();
 		i = Int32.Parse(s);
 		//nested if-else selection
 		if(i == 0)
{
		Console.WriteLine("The number is zero");
}
 	else if(i > 0)
{
		Console.WriteLine("The number {0} is positive",i);
}
	else
{
		Console.WriteLine("The number {0} is negative",i);
}
 }
}
 
The above if statement example reads a number from console. Input coming from console is in string format. Int32.parse(string) is used to convert string literal to integer.
 
The variable i is the object of evaluation here. c++ programmers can see that the use of if statement is same in c#. Halt it. There is one difference. The expression in an if statement must resolve to bool value. Take a look at following code.
 
using System;
class IfTest2 
{
 	public static void Main()
 	{
 		if(1)
 		{
 			Console.WriteLine("The if statement executed");
 		}
 	}
}
 
When this code is complied by c# compiler, it will give the error “constant value 1 an not be converted to bool”. Conditional ‘OR’ (||) and conditional ‘AND’ (&&) operators are used in the same manner. Consider the following code.
 
LeapTest.cs
 
//Leap year
using System;
class LeapTest 
{
 	public static void Main()
 	{
 		int year;
 		Console.WriteLine("enter the year value (yyyy) :");
 		year = Int32.Parse(Console.ReadLine());
 		if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 )
{
 		Console.WriteLine ("The year {0} is leap year ",year);
}
 	else
{
 		Console.WriteLine ("The year {0} is not leap year ",year);
 	}
}
}
 
Switch statements
 
The “switch” statement is similar toto nested if-else form of if statement. The only difference is that each if compares the result of the expression with a different value.
 
Example:
 
if (day==0)
	dayName=”Sunday”;
else if (day==0)
	dayName=”Monday”; 
else if (day==0)
	dayName=”Tuesday”; 
else if (day==0)
	dayName=”Wednesday”; 
else if (day==0)
	…….
else
	dayName=”Unknown”; 
 
In these circumstances, you can frequently rewrite the nesting if statement as a switch statement to make your program more efficient and more readable. The general syntax of switch statement is as follows (switch, case, default and break are keywords):
 
switch( controllingExpression )
{
case constantExpression :
	statements
	break;
case constantExpression :
	statements
	break;
…
default :
	statements
	break;
}

 
The controlling Expression is evaluated once, and the statements below the case whose constant Expression value is equal to the result of the controlling Expression run as fast as the break statement. The switch statement then finishes and the program continues at the first statement after the closing brace of the switch statement.
 
If none of the constant Expression values are equal to the value of the controlling Expression, the statement below the optional default label run. You can rewrite the previous nested if statements as the following switch statement:
 
SwitchTest1.cs
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
namespace ConsoleApplication4
{
class SwitchTest1 
{
 	public static void Main()
 	{
 		int day = 3;
 		switch(day)
 		{
 			case 0 :
 			 Console.WriteLine("dayName = “Sunday”");
 			 	break; 
 			case 1 :
 			 Console.WriteLine("dayName = “Monday”");
 			 	break; 
 			case 2 :
 			 Console.WriteLine("dayName = “Tuesday”");
 			 	break; 
 			case 3 :
 			 Console.WriteLine("dayName = “Wednesday”");
 			 	break; 
 			case 4 :		
 			 
 			 	break;
 			default :
 			 	Console.WriteLine("default");
 			break;
 		}
           Console.ReadLine();
        }
    }

}

 
The difference here is if you try to compile above code without putting break statement in case 1, compiler will raise an error “control can not fall through from one case label”. I’m sure c++/Java programmers are going to love this.
 
Loops
 
In c#, there are four types of iteration constructs rather than three. There are familiar for, do-while, while loops and a new one from Visual basic, foreach.
 
The While Statements
 
In this looping statements, we use the while keyword followed by terminating Condition. Before executing the loop it checks the terminating condition, if the condition is true then the loop will be continued otherwise exit from the loop. The general syntax of while statement is:
 
while( terminatingCondition )
{

//Body of while loop

}

 
Here is a simple example.
 
WhileTest.cs
 
//find out the number of digits in a given number
using System;
class WhileTest 
{
 	public static void Main()
 	{
 		int i = 123;
 		int count = 0;
 		int n = i;
 		//while loop may execute zero times.
 		while(i > 0)
 		{
 			++count; 
 			i = i/10;
 		}
 		Console.WriteLine("Number {0} contains {1} digits.",n,count);
 	}
}
 
The above code shows simple while loop, which finds out the number of digits in a number. for a given number i = 123, the loop will execute tree times and hence the value of count will be three at the end of the while loop.
 
The above code has one logical flaw. If the number i is set to 0, the output of the code will be “Number 0 contains 0 digits.” Actually number 0 is of one digit. Since the condition for the while loop i>0 is false from beginning for the value i=0, the while loop won’t execute any time and count will be zero. So to remove this type of ambiguity another loop statement is here i.e. do….while statement.
 
The do…while statement
 
In this looping structure, this do…while loop will be executed at least once, after then it checks the termination condition. If the condition is true then the loop will be continued otherwise exit from the loop. The general syntax of do…while statement is:
 
do
{
	//Body of do…while statement
}while(terminating condition);
 
Here is a simple example.
 
DoTest.cs
 
//find out the number of digits in a given number. 
using System;
class DoTest 
{
 	public static void Main()
 	{
 		int i = 0;
 		int count = 0;
 		int n = i;
 		do
 		{
 			++count; 
 			i = i/10;
 		}while(i > 0);
 		Console.WriteLine("Number {0} contains {1} digits.",n,count);
 	}
}
 
The Do-While construct checks condition in the end of the loop. Thus Do-while loop will execute at least once even though the condition to be checked is false from beginning.
 
The for Statement
 
In this looping structure, we use for keyword. In for loop we initialize the iteration variable, termination condition and incrementing condition with in parenthesis separated by semi colon. The “for” loop is good when we know how many times the loop needs to be executed. The general syntax of for loop is:
 
for(initializing variable; terminating 
condition; incrementing variable)
{
	//body of for loop
}
 
Here is a simple example.
 
Fortest.cs
 
//For loop with break and continue statements
using System;
class ForTest 
{
 	public static void Main()
 	{
 		for(int i = 0 ; i < 20 ; ++i)
 		{
 			if(i == 10)
 				break;
 			if(i == 5)
 				continue;
 			Console.WriteLine( i );
 		}
 	}
}
 
The output of the above code will be:
0
1
2
3
4
6
7
8
9
 
Isn’t it self explanatory? When I become 5, the loop will skip over the remaining statements in the loop and go back to the post loop action. Thus 5 is not part of the output. When i becomes 10, control will break out of the loop.
 
The foreach statement
 
This statement allows iterating over the elements in arrays and collections. The syntax of foreach loop is:
 
foreach (variable1 in variable2)
{
//Body of foreach loop
}
 
Here is a simple example.
 
ForEach.cs
 
//foreach loop 
using System;
class ForEach 
{
 	public static void Main()
 	{
 		string[] a = {"Chirag", "Bhargav", "Tejas"};
 		foreach(string b in a)
 			Console.WriteLine(b);
 	}
}
 
Within the foreach loop parenthesis, the expression is made up of two parts separated by keyword in. The right hand side of in is the collection and left hand side is the variable with type identifier matching to whatever type the collection returns.
 
Every time the collection is queried for a new value. As long as the collection returns value, the value is put into the variable and expression will return true. When the collection is fully traversed, the expression will return false and control will be transferred to the next statement after a loop.
 
Notes: The main drawback of ‘foreach’ loops is that each value extracted (held in the given example by the variable ‘b’) is read-only.
 
Jump and Selection Statements
 
There are five types of jump statements in C# i.e. 
?	break
?	continue
?	goto
?	return
?	throw (this jump statement will be described in chapter Exception and Error handling )
 
break
 
The ‘break’ statement breaks out of the ‘while’ and ‘for’ loops. It is also used within ‘switch’ statements. The following code gives an example.
 
int a = 0;
	while (true)
	{
	    System.Console.WriteLine(a);
	    a++;
	    if (a == 5)
	        break;	//breaking the while loop
	}
 
The output of the loop is the numbers from 0 to 4.
 
continue
 
The ‘continue’ statement can be placed in any loop structure. When it executes, it moves the program counter immediately to the next iteration of the loop. The following code example uses the ‘continue’ statement to count the number of values between 1 and 100 inclusive that are not multiples of seven. At the end of the loop the variable y holds the required value.
 
int y = 0;
	for (int x = 1; x < 101; x++)
	{
	   	if ((x % 7) = = 0)
			{
	        	continue;
			}
	     	y++;
	}
 
goto
 
Use of goto statement is not recommended by any programmers . The ‘goto’ statement is used to make a jump to a particular labeled part of the program code. It is also used in the ‘switch’ statement described below. We can use a ‘goto’ statement to construct a loop, as in the following example (but again, this usage is not recommended):
 
int a = 0;
	start:
	System.Console.WriteLine(a);
	a++;
	if (a < 5)
	    goto start;

 
‘Switch’ statements provide a clean way of writing multiple if – else statements. In the following example, the variable whose value is in question is ‘a’. If a equals 1, then the output is ‘a>0’; if a equals 2, then the output is ‘a>1 and a>0’. Otherwise, it is reported that the variable is not set.
 
switch(a)
	{
	    case 2:
	        Console.WriteLine("a>1 and ");
	        goto case 1;
	    case 1:
	        Console.WriteLine("a>0");
	        break;
	    default:
	        Console.WriteLine("a is not set");
	        break;
	}
 
Each case (where this is taken to include the ‘default’ case) will either have code specifying a conditional action, or no such code. Where a case does have such code, the code must (unless the case is the last one in the switch statement) end with one of the following statements:
 
break;
goto case k; (where k is one of the cases specified)
goto default;
 
From the above it can be seen that C# ‘switch’ statements lack the default ‘fall through’ behaviour found in C++ and Java. However, program control does fall through wherever a case fails to specify any action. The following example illustrates this point; the response “a>0” is given when a is either 1 or 2.
 
switch(a)
	{
	    case 1:
	    case 2:
	        Console.WriteLine("a>0");
	        break;
	    default:
	        Console.WriteLine("a is not set");
	        break;
	}
 
return
 
Methods can either return a type or not. A method that doesn’t return a type must give its return type as ‘void’. A method that does return a type must name the type returned.
 
A method will stop and return a value if it reaches a ‘return’ statement at any point in its execution. The type returned is given at the end of such a return statement; its type must correspond with that specified in the method declaration. The following piece of code illustrates this point.
 
public static int exampleMethod()
	{
	    int i =0;
	    // process i	
    
	    return i;
	}

Check Also

Exceptions In C#

System.Exception is the base class for all other exceptions. Below this level are the System.ApplicationException …