Jump to content
xisto Community

C# Tutorial : Lesson 3 - Programming Constructs

Recommended Posts

Conditional Branching


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



if ( < condition > )









The else part is optional and can be omitted. The working of if .. else construct 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 if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, 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 if is 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 here would 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 in will be displayed.


The condition inside the if statement 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 ToBoolean function 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 < 18 and 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 true and the message - You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and 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. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message - Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.


switch .. case Construct

Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.



switch (< expression >)


case Expression_1;




case Expression_2;








break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.




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 break statement.


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:-


The for loop

This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-


for(< initialization >;< condition >;< increment/decrement >)





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 for statement and leave out the initialization block. The code would look like this (; I <= 1000; I++). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).


Another variation of a for statement is the empty loop which does not contain any body: for(int I = 1; I <= 1000; I++);


Such a for statement is followed by the semicolon.


The while loop

The for loop 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 while statement.



while(< condition >)





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 Continue which 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 while loop would keep on executing.


Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 - 1000 using while.


int I = 1;while(I <= 1000){	Console.WriteLine(I);	I++;}

The do while loop

The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program 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 true so 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 for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.


Previous Tutorial - Lesson 2 - Variables & Operators


Next Tutorial - Lesson 4 - Object Oriented Programming


Lesson: 1 2 3 4 5 6 7

Edited by turbopowerdmaxsteel (see edit history)

Share this post

Link to post
Share on other sites

I need this programWrite a pgm to identify whether a character entered by a user is a vowel or a consonant-reply by darlee

Share this post

Link to post
Share on other sites
typecasting for switchcase "value"C# Tutorial : Lesson 3 - Programming Constructs

I have an query regarding the typecasting of the "var" used in the switch case statements..

Program as below

char var;


Case: 10

...Do some thing;

Case: 20

...Do some thing.

My doubt is do we explictly typecast the var to 'int' datatype in the statement switch((int)var)?


-question by v_tarasu

Share this post

Link to post
Share on other sites
if-then statementC# Tutorial : Lesson 3 - Programming Constructs

prgramminig constructs

if-then statement




for each-next


-reply by prosper


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.