Advertisment

Program Control in C#

author-image
PCQ Bureau
New Update

One of the first things taught in programming is how to control the program flow, how to affect the way the executed code works. Use of conditionals, loops, and branching helps us control the way the code works when executed. And that’s what program control is all about. In this article, we'll see the fundamentals of C# program control.

Advertisment

The if

The if statement lets us evaluate a condition for being true, and then executes the appropriate code. Its general syntax is as follows:

if (condition)



execute statement 1




execute statement 2>
Advertisment

Starting from top, this general syntax means that the condition enclosed within brackets after if will be checked for being true. If the condition evaluates to true, then statement 1 is executed. However, if the condition evaluates to false, then statement 2 is executed because it comes after the else clause. Statements after the else clause are executed only when the condition following if doesn’t evaluate

to true.

If you notice, the else clause and the statement 2 are enclosed within box brackets. This means that the else and hence the corresponding statement 2 are optional. We could have an if statement coded something like this as well:

if (condition)



execute statement 1


statement 2
Advertisment

What this means is that if the condition evaluates to true, only then statement 1 will be executed. Statement 2¸ on the other hand, shall be executed irrespective of whether the if condition evaluates to true or false, since it doesn't follow an else clause. Now, if we were to have the code execute more than one statement either upon the condition being evaluated to true or false, all we have to do is to enclose the statements within curly brackets, as shown below:

if (condition)



{


execute statement 1


execute statement 2


execute statement 3


}




{


execute statement 4


execute statement 5


execute statement 6


}>








As explained earlier, the else clause and its corresponding statement or set of statements are optional, as indicated above by being enclosed within box brackets. We can thus see that the program control is being influenced by just one condition. However, if needed, we can combine the else clause and the if statement to provide multiple conditions for determining the program control, as shown below:

Advertisment
if (condition1)



execute statement 1


else if (condition2)


execute statement 2


else


execute statement 3



In the syntax above, first conditon1 is evaluated. If it is false, the if statement conjoined with the first else clause is executed, and condition2 is evaluated. If it is evaluated to true, then statement 2 is executed, else statement 3 is finally executed. Now, let's take a look at the C# specific for the if statement. C# requires that the condition being evaluated gets evaluated to a boolean value. This is in contrast to C/C++ where any non-zero value was taken to be true and a zero value was taken to be false. Thus, the following code would break in C#:

int a=1;



if (a)


// condition is true


else


// condition is false


Advertisment

The corrected version would be like this:

int a=1;



if (a>0)


// condition is true


else


// condition is false


The source code of this article carries a C# program to use the if statement to check for a number entered by the user for being even or odd. You refer to it to see the if in action. Now, let’s move onto looping.

Advertisment

Looping

Looping is the programmatic implementation of code to execute a number of times in succession, either running infinitely, or controlled by some condition. In C#, various statements help us implement loops.

Anyone who has ever programmed would know the for statement. Its syntax is pretty much the same as in C++, and is shown below:

Advertisment
for (initializer; condition; iterator)



Statement;

Here, initializer expression lets you declare a variable local to the loop and set its value. You can declare the variable outside the loop, and simply use the initializer expression to initialize the variable’s value. The condition part is used to specify the condition, which will be evaluated, and if it evaluates to true, only then the statement part will be executed. Note that the statement can comprise of a single C# statement or multiple C# statements enclosed within curly brackets. After the statement portion is executed once, the iterator portion comes into play, and is usually used to increment the value of the loop variable that was initialized using the initializer expression. A simple example would be like this:

for(int i=1;i<=10;i++)



Console.WriteLine(“{0}”,i);

The initializer portion declares a variable called i and initializes its value to 1. The condition portion is checked next, and if it evaluates to true, the statement portion is then executed. The iterator portion then increments the value of

i, and the condition is tested again. If it is true, the statement portion is then executed, and again, the iterator portion is called. The looping continues until the condition evaluates to false, after which the loop stops. Hence, the above shown loop will print the count from 1 to 10. In the following loop:

for(int i=0;i>0;i++)



Console.WriteLine(“{0}”,i);

the loop won’t execute because when the condition is evaluated, it evaluates to false since i was initialized to zero, while the condition expects it to be greater than zero. Note that the all the three parts of the for loop are optional. Thus, we could have a for loop as shown below:

for(;;)



Console.WriteLine(“{0}”,i);

Since there aren’t any conditions being evaluated, this loop is infinite in nature. If we wish to come out of an infinite loop we should use the break keyword. We check for the condition within the loop and when the condition evaluates to true, we execute a break statement:

int i=1;



for(;;)


{


if (i<=10)


{


Console.WriteLine(“{0}”,i);


i++; // increment i


}


else


break;


}








In the above infinite loop, we initialize the variable to be utilized outside the loop, and then check the condition within the loop. If the value of the variable is less than or equal to 10, the number shall be displayed on the screen, and then the value of the variable is incremented by one. When it’s more than 10, the else clause gets executed and hence, the break statement gets executed, and the control breaks out of the infinite for loop. Thus, effectively, this loop and the one previously described are equivalent.

And now we come to the while and the do-while loops. Both are almost identical to each other except that in while loop, the condition is evaluated before executing the statements to be executed, and in the do-while, it is evaluated after executing the statements to be executed. The syntax for them is as follows:

while(condition)



{


// statements to be executed come here


}


do


{


// statements to be executed come here


} while(condition);





In the while loop, the statements within the brackets are executed only when the condition evaluates to true. Upon executing the statements, the condition is checked again. The process goes on until the condition evaluates to false. Same is the case for the do-while loop, except that when the loop is executed for the first time, the enclosed statements are executed, and then the condition is checked. Only if the condition evaluates to true are the statements executed again.

Another loop statement which is specific to C# is the foreach statement. It lets you iterate through elements in arrays and collections (defined as a group of items of a similar kind, like all ints or all longs). If you have ever programmed in Visual Basic, you will already be familiar with this statement. Let's see an example of its usage:

int <> arr = new int <> {1,2,3,4,5,6,7,8,9,10};



foreach(int i in arr)


Console.WriteLine(“{0}”,i);

What this statement above tells the compiler is to look for each integer in the collection

arr, and each time one is found, represent it with variable i, which is of the same type as the elements being iterated from the collection. The variable i can then be used to work upon the iterated contents of the collection.

The switch

The switch statement is used to selectively execute code, depending upon the value of the expression, unlike the if statement that depends upon the boolean value of the expression. Let's see an example:

switch(v)



{


case 1:


Console.WriteLine(“Value is 1”);


break;


case 2:


Console.WriteLine(“Value is 2”);


break;


default:


Console.WriteLine(“Unknown value”);


}








The expression between the brackets after the switch keyword is called the switch expression, and depending upon it, that code is executed whose case has the same value as that of the switch expression. So, if v were to have a value of 2, the second case would have been executed. To catch a value which is not caught by any of the cases, there is the default case. Note that all case clauses must be followed by statements to be executed, followed by a break statement to indicate the end of the case. Unlike C/C++, where omitting the case would have resulted in a fall through to the next case, in C#, the compiler would result in an error. You cannot fall through one case to another. So, this code is erroneous: 

switch(v)



{


case 1:


Console.WriteLine(“Value is 1”);


case 2:


Console.WriteLine(“Value is 2”);


break;


default:


Console.WriteLine(“Unknown value”);


}







If you wish to fall through then you must use the goto statement which branches off to the

relevant case:

switch(v)



{


case 1:


Console.WriteLine(“Value is 1”);


goto case 2;


case 2:


Console.WriteLine(“Value is 2”);


break;


default: Console.WriteLine(“Unknown value”);


}







You may also fall through if the successive cases have no lines of code between them:

switch(v)



{


case 1:


case 2: Console.WriteLine(“Value is 1 or 2”);


break;


default:


Console.WriteLine(“Unknown value”);


}





The fundamentals of program control in C# are almost the same as in C/C++, but you need to take care of certain specifics . The source code in the accompanying CD illustrates the implementation of all the constructs we’ve discussed here.

Kumar Gaurav Khanna

Advertisment