Operators and Control Flow
Posted by Ravi Varma Thumati on February 12, 2015
Operators
An operator is a symbol that causes C# to take an action. The C# primitive types (e.g., int) support a number of operators such as assignment, increment, and so forth.
The Assignment Operator (=)
The section titled “Expressions,” earlier in this chapter, demonstrates the use of the assignment operator. This symbol causes the operand on the left side of the operator to have its value changed to whatever is on the right side of the operator.
Mathematical Operators
C# uses five mathematical operators: four for standard calculations and a fifth to return the remainder in integer division. The following sections consider the use of these operators.
Simple arithmetical operators (+, -, *, /)
C# offers operators for simple arithmetic: the addition (+), subtraction (-), multiplication (*), and division (/) operators work as you might expect, with the possible exception of integer division.
Relational Operators
Relational operators are used to compare two values, and then return a Boolean (true or false). The greater-than operator (>), for example, returns true if the value on the left of the operator is greater than the value on the right. Thus, 5 > 2 returns the value true, while 2 > 5 returns the value false.
The relational operators for C# are shown in Table. This table assumes two variables: bigValue and smallValue, in which bigValue has been assigned the value 100 and smallValue the value 50.
C# relational operators (assumes bigValue = 100 and smallValue = 50) |
|||
Name | Operator | Given this statement | The expression evaluates to |
Equals | ==
|
bigValue == 100bigValue == 80
|
true false
|
Not equals | !=
|
bigValue != 100bigValue != 80
|
falsetrue
|
Greater than | >
|
bigValue > smallValue
|
true
|
Greater than or equals | >=
|
bigValue >= smallValuesmallValue >= bigValue
|
truefalse
|
Less than | <
|
bigValue < smallValue
|
false
|
Less than or equals | <=
|
smallValue <= bigValuebigValue <= smallValue
|
truefalse |
Use of Logical Operators with Conditionals
If statements (discussed earlier in this chapter) test whether a condition is true. Often you will want to test whether two conditions are both true, and whether only one is true, or none is true. C# provides a set of logical operators for this, as shown in below table. This table assumes two variables, x and y, in which x has the value 5 and y the value 7.
C# logical operators (assumes x = 5, y = 7) |
|||
Name | Operator | Given this statement | The expression evaluates to |
and
|
&&
|
(x == 3) && (y == 7)
|
false
|
or
|
||
|
(x == 3) || (y == 7)
|
true
|
not
|
!
|
! (x == 3)
|
true
|
The and operator tests whether two statements are both true. The first line in Table 3-4 includes an example that illustrates the use of the and operator:
(x == 3) && (y == 7)
The entire expression evaluates false because one side (x == 3) is false.
With the or operator, either or both sides must be true; the expression is false only if both sides are false. So, in the case of the example in Table 3-4:
(x == 3) || (y == 7)
the entire expression evaluates true because one side (y==7) is true.
With a not operator, the statement is true if the expression is false, and vice versa. So, in the accompanying example: ! (x == 3)
Conditional Branching Statements
A conditional branch is created by a conditional statement, which is signaled by keywords such as if, else, or switch. A conditional branch occurs only if the condition expression evaluates true.
if…else statements
if…else statements branch based on a condition. The condition is an expression, tested in the head of the if statement. If the condition evaluates true, the statement (or block of statements) in the body of the if statement is executed.
if statements may contain an optional else statement. The else statement is executed only if the expression in the head of the if statement evaluates false:
if (expression) statement1[else statement2]
This is the kind of if statement description you are likely to find in your compiler documentation. It shows you that the if statement takes a Boolean expression (an expression that evaluates true or false) in parentheses, and executes statement1 if the expression evaluates true. Note that statement1 can actually be a block of statements within braces.
if…else statements
using System;
class Values
{
static void Main()
{
int valueOne = 10;
int valueTwo = 20;
if (valueOne > valueTwo)
{
Console.WriteLine(
“ValueOne: {0} larger than ValueTwo: {1}”,
valueOne, valueTwo);
}
else
{
Console.WriteLine(
“ValueTwo: {0} larger than ValueOne: {1}”,
valueTwo, valueOne);
}
valueOne = 30; // set valueOne higher
if (valueOne > valueTwo)
{
valueTwo = valueOne++;
Console.WriteLine(“\nSetting valueTwo to valueOne value, “);
Console.WriteLine(“and incrementing ValueOne.\n”);
Console.WriteLine(“ValueOne: {0} ValueTwo: {1}”,
valueOne, valueTwo);
}
else
{
valueOne = valueTwo;
Console.WriteLine(“Setting them equal. “);
Console.WriteLine(“ValueOne: {0} ValueTwo: {1}”,
valueOne, valueTwo);
}
}
}
Nested if statements
It is possible, and not uncommon, to nest if statements to handle complex conditions. For example, suppose you need to write a program to evaluate the temperature, and specifically to return the following types of information.
- If the temperature is 32 degrees or lower, the program should warn you about ice on the road.
- If the temperature is exactly 32 degrees, the program should tell you that there may be ice patches.
There are many good ways to write this program. Example 3-8 illustrates one approach, using nested if statements.
Example 3-8. Nested if statements
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace NestedIf
{
class NestedIf
{
static void Main( )
{
int temp = 32;
if ( temp <= 32 )
{
Console.WriteLine( “Warning! Ice on road!” );
if ( temp == 32 )
{
Console.WriteLine(
“Temp exactly freezing, beware of water.” );
}
else
{
Console.WriteLine( “Watch for black ice! Temp: {0}”, temp );
} // end else
} // end if (temp <= 32)
} // end main
switch statements: an alternative to nested ifs
Nested if statements are hard to read, hard to get right, and hard to debug. When you have a complex set of choices to make, the switch statement is a more readable alternative. The logic of a switch statement is “pick a matching value and act accordingly.”
switch (expression)
{
case constant-expression:
statement jump-statement [default: statement]
}
As you can see, like an if statement, the expression is put in parentheses in the head of the switch statement. Each case statement then requires a constant expression; that is, a literal or symbolic constant or an enumeration.
If a case is matched, the statement(s) associated with that case is executed. This must be followed by a jump statement. Typically, the jump statement is break, which transfers execution out of the switch.
The switch statement
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace SwitchStatement
{
class SwitchStatement
{
static void Main( string[] args )
{
const int Democrat = 0;
const int LiberalRepublican = 1;
const int Republican = 2;
const int Libertarian = 3;
const int NewLeft = 4;
const int Progressive = 5;
int myChoice = Libertarian;
switch ( myChoice )
{
case Democrat:
Console.WriteLine( “You voted Democratic.\n” );
break;
case LiberalRepublican: // fall through
//Console.WriteLine(
//”Liberal Republicans vote Republican\n”);
case Republican:
Console.WriteLine( “You voted Republican.\n” );
break;
case NewLeft:
Console.WriteLine( “NewLeft is now Progressive” );
goto case Progressive;
case Progressive:
Console.WriteLine( “You voted Progressive.\n” );
break;
case Libertarian:
Console.WriteLine( “Libertarians are voting Republican” );
goto case Republican;
default:
Console.WriteLine( “You did not pick a valid choice.\n” );
break;
}
Console.WriteLine( “Thank you for voting.” );
}
}
}
Iteration Statements
C# provides an extensive suite of iteration statements, including for, while and do…while loops, as well as foreach loops (new to the C family but familiar to VB programmers). In addition, C# supports the goto, break, continue, and return jump statements.
The goto statement
The goto statement is the seed from which all other iteration statements have been germinated. Unfortunately, it is a semolina seed, producer of spaghetti code and endless confusion. Most experienced programmers properly shun the goto statement, but in the interest of completeness, here’s how you use it:
- Create a label.
- goto that label.
Example 3-10. Using goto
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace UsingGoTo
{
class UsingGoTo
{
static void Main( string[] args )
{
int i = 0;
repeat: // the label
Console.WriteLine( “i: {0}”, i );
i++;
if ( i < 10 )
goto repeat; // the dastardly deed
return;
}
}
}
The while loop
The semantics of the while loop are “while this condition is true, do this work.” The syntax is:
while (expression) statement
As usual, an expression is any statement that returns a value. While statements require an expression that evaluates to a Boolean (TRue/false) value, and that statement can, of course, be a block of statements. Example 3-11 updates Example 3-10, using a while loop.
Example 3-11. Using a while loop
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace WhileLoop
{
class WhileLoop
{
static void Main( string[] args )
{
int i = 0;
while ( i < 10 )
{
Console.WriteLine( “i: {0}”, i );
i++;
}
return;
}
}
}
The do…while loop
A while statement may never execute if the condition tested returns false. If you want to ensure that your statement is run at least once, use a do…while loop:
do statement while expression
An expression is any statement that returns a value. Example 3-12 shows the do… while loop.
Example 3-12. The do…while loop
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace DoWhile
{
class DoWhile
{
static void Main( string[] args )
{
int i = 11;
do
{
Console.WriteLine( “i: {0}”, i );
i++;
} while ( i < 10 );
return 0;
}
}
}
Here i is initialized to 11 and the while test fails, but only after the body of the loop has run once.
The for loop
A careful examination of the while loop in Example 3-11 reveals a pattern often seen in iterative statements: initialize a variable (i = 0), test the variable (i < 10), execute a series of statements, and increment the variable (i++). The for loop allows you to combine all these steps in a single loop statement:
for ([initializers]; [expression]; [iterators]) statement
The for loop is illustrated in Example 3-13.
Example 3-13. The for loop
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ForLoop
{
class ForLoop
{
static void Main( string[] args )
{
for ( int i = 0; i < 100; i++ )
{
Console.Write( “{0} “, i );
if ( i % 10 == 0 )
{
Console.WriteLine( “\t{0}”, i );
}
}
return ;
}
}
}
Output:
0 0
1 2 3 4 5 6 7 8 9 10 10
11 12 13 14 15 16 17 18 19 20 20
21 22 23 24 25 26 27 28 29 30 30
31 32 33 34 35 36 37 38 39 40 40
41 42 43 44 45 46 47 48 49 50 50
51 52 53 54 55 56 57 58 59 60 60
61 62 63 64 65 66 67 68 69 70 70
71 72 73 74 75 76 77 78 79 80 80
81 82 83 84 85 86 87 88 89 90 90
91 92 93 94 95 96 97 98 99
This for loop makes use of the modulus operator described later in this chapter. The value of i is printed until i is a multiple of 10:
The foreach statement
The foreach statement is new to the C family of languages; it is used for looping through the elements of an array or a collection.
foreach(type identifier in
expression)
embeddedstatement
Example:
foreach (char letter in email)
{
if(!insideDomain)
{
if (letter == ‘@’)
{
insideDomain = true;
}
continue;
}
Console.Write(letter);
}
Statement | General Syntax Structure | Example |
if statement | if(booleanexpression)
embeddedstatement
|
if (input == “quit”)
{ Console.WriteLine(“Game end”); return; }
|
if(booleanexpression)
embeddedstatement else embeddedstatement
|
if (input == “quit”)
{ Console.WriteLine(“Game end”); return; } else GetNextMove();
|
|
while statement | while(booleanexpression)
embeddedstatement
|
while(count < total)
{ Console.WriteLine(“count = {0}”, count); count++; }
|
do while statement | do
embeddedstatement while(booleanexpression);
|
do
{ Console.WriteLine(“Enter name:”); input = Console.ReadLine(); } while(input != “exit”);
|
for statement | for(forinitializer;
booleanexpression; foriterator) embeddedstatement
|
for (int count = 1; count <= 10; count++)
{ Console.WriteLine(“count = {0}”, count); }
|
foreach statement | foreach(type identifier in
expression) embeddedstatement
|
foreach (char letter in email)
{ if(!insideDomain) { if (letter == ‘@’) { insideDomain = true; } continue; } Console.Write(letter); }
|
continue statement | continue; | |
switch statement | switch(governingtype
expression) { … case constexpression: statementlist jumpstatement default: statementlist jumpstatement }
|
switch(input)
{ case “exit”: case “quit”: Console.WriteLine(“Exiting app….”); break; case “restart”: Reset(); goto case “start”; case “start”: GetMove(); break; default: Console.WriteLine(input); break; }
|
break statement | break; | |
goto statement | goto identifier; | |
goto case const-expression | ||
goto default; |
Leave a comment