09 Apr, 2007 · 8 minutes read
By branching we imply, having different paths for execution. Conditions are used to determine which statements need to be executed. Suppose, you have a program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.
C# provides the following conditional constructs:-
if .. else
Syntax:-
if (
{
statements
}
else
{
statements
}
The else part is optional and can be omitted. The working of if .. elseconstruct is very simple and follows the pattern – If this is true I’ll do that or else I’ll do something else. The statements included within the ifblock are executed when the condition specified in if, is true, otherwise the statements inside the elseblock are executed. In case, there is no elsestatement, the execution flow continues to the proceeding statements.
Here’s an example:-
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
Console.WriteLine("You are not permitted in here.");
}
else
{
Console.WriteLine("You may come in.");
}
Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside ifis evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 - Console.WriteLine("You are not permitted in here.");and the message You are not permitted in herewould be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come inwill be displayed.
The condition inside the ifstatement can be composed of a complex expression chained by the logical operators. For Example:-
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian == false))
{
Console.WriteLine("You are not permitted in here.");
}
else
{
Console.WriteLine("You may come in.");
}
At line 4 the user's response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBooleanfunction is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18and WithGuardian == false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to trueand the message - You are not permitted in herewill be displayed. For any other combination, the final expression would be equivalent to falseand the message - You may come in will be displayed.
A number of conditions can be chained by using else if as follows:-
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
Console.WriteLine("Welcome Programmer");
}
else
{
Console.WriteLine("Welcome dear Customer");
}
In this case, if the salary supplied by the user is greater than 250000, the message - Welcome Mr. CEOwill be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairmanelse if the salary is greater than 0, the message - Welcome Programmerwill be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customerwill be the output.
Switch casefacilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a caseconstruct.
Syntax:-
switch(
{
caseExpression_1;
statements
break;
caseExpression_2;
statements
break;
...
}
breakis a C# keyword, which is used to exit the body of a switch, foror whileloop. Equivalent to the else construct is the defaultcase. Statements within the default case are executed when no other condition holds true.
Example:-
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("There are only 12 Months.");
break;
}
Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months.will be displayed.
Multiple Values can be made to lead to the same block of statements by excluding the breakstatement.
Console.WriteLine("Enter a number (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
case 2:
case 3:
case 5:
case 7:
Console.WriteLine("The number is prime.");
break;
case 1:
case 9:
Console.WriteLine("The number is odd.");
break;
case 4:
case 6:
case 8:
Console.WriteLine("The number is Even");
break;
default:
Console.WriteLine("The number is not in range.");
break;
}
A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 - 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 - 1000? Using the computer's iterative power is a much better approach.
C# supports 3 kinds of loops which are discussed below:-
This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of forloop is as follows:-
for(< initialization>;< condition>;< increment/decrement>)
{
statements
}
To print numbers within a range, say 1 - 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.
for(int I = 1; I <= 1000; I )
{
Console.WriteLine(I);
}
Lets break the for statement down:-
Initialization: int I = 1
Condition: I <= 1000
Increment: I
All the parts here are optional and can be left out. So, you can initialize the variable I, above the forstatement and leave out the initialization block. The code would look like this (; I <= 1000; I ). Similarly, you could remove the conditionpart to make the loop infiniteor you can include the increment statement within the body of the for statement itself (inside the { and } brackets).
Another variation of a forstatement is the empty loop which does not contain any body:-
for(int I = 1; I <= 1000; I++);
Such a forstatement is followed by the semicolon.
The forloop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the whilestatement.
Syntax:-
while(
{
statements
}
We don't have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.
bool Continue = true;
while(Continue == true)
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");
Continue = Convert.ToBoolean(Console.ReadLine());
}
We have declared a boolean variable Continuewhich we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user's choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the whileloop would keep on executing.
Anything that can be implemented using forloop, can also be done using the whileloop. Below is the code to print numbers from 1 - 1000 using while.
int I = 1;
while(I <= 1000)
{
Console.WriteLine(I);
I++;
}
The do whileloop is a variation of the whileloop in which the condition is evaluated at the endof the loop. Thus, the loop is executed at least once. Recall the first whileprogram we did. The bool variable continue stores the user's choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value trueso that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.
bool Continue;
do
{
int A;
Console.WriteLine("Please Enter a Number");
A = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Continue (True/False)");
Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);
Note: The while part in the do while loop needs to be terminated with the semicolon.
Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the forloop for arithmetic operations, whileloop for non-arithmetic ones and the do-whileloop when the loop must execute at least once.