Download Control Statements - Programming Using C Sharp - Lecture Slides and more Slides Advanced Algorithms in PDF only on Docsity!
Control Statements
if-else, switch, while, for, do-while
Conditional Statements
So far statements of our programs execute
sequentially one after another.
What happens when
we want to execute a statement depending on a condition? e.g. If there is enough money in the bank account, give the money we want to execute one statement when a condition holds and another statement when a condition does not hold? e.g. If dollar is high, sell dollar. Otherwise, buy dollar. we want to select from many statements according to one or more criteria ( selection ). e.g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy YTL.
You achieve conditional execution with if-else
statements
Another Syntax (without { })
if (< condition >) <s tatement_true> ; else <s tatement_false> ;
if (< condition >) <s tatement_true> ;
- Can be used when there is only one statement
- Not suggested (we will see why)
Flow diagram of if-else
test condition
true statements
true
next statement
false
false statements
Boolean type and expressions
The condition in an if statement must be a
Boolean expression (named for George Boole)
Values are true or false bool is a built-in value type like int, double
int degrees; bool isHot = false;
Console.WriteLine("enter temperature: “); degrees = Convert.ToInt32(Console.ReadLine()); if (degrees > 35) { isHot = true; }
Conditional operator (?:)
- The conditional operator ( ?: ) can be used in place of an
if…else statement.
Console.WriteLine( grade >= 60? "Passed" : "Failed" );
- The first operand is a boolean expression that evaluates to true or false.
- The second operand is the value if the expression is true
- The third operand is the value if the expression is false.
8
Logical operators
• Boolean expressions can be combined
using logical operators: AND, OR, NOT
– In C# we use && ||! respectively
A B A || B A && B true true true true true false true false false true true false false false false false
A! A true false false true
Example
- Range check: between 0 and 100 (includes 0 and 100), or not? If so, display a message saying that the number is in the range. If not, the message should say “out of the range”.
- Solution 1: using logical AND operator
if (num >= 0 && num <= 100) Console.Write("number is in the range"); else Console.Write("number is out of range");
- Solution 2: using logical AND and NOT operators
if (! (num >= 0 && num <= 100) ) Console.Write("number is out of range"); else Console.Write("number is in the range");
- Solution 3: using logical OR operator
if (num < 0 || num > 100) Console.Write("number is out of range"); else Console.Write("number is in the range");
Operator Precedence - Revisited
• Upper operator groups have precedence
Operator Explanation Associativity
- -! (^) plus and minus signs, logical NOT right-to-left
- / % (^) multiplication, division and modulus left-to-right
- addition, subtraction^ left-to-right < <= > >= inequality comparison operators left-to-right == != equal, not equal comparison left-to-right && logical and left-to-right || logical or^ left-to-right = += -= *= /= %=
assignment operators right-to-left
Nested if statements
- if/else statements are inside other if/else statements
- Method to select from multiple choices
- Example: input a numeric grade and convert to letter grade
90 .. 100 A 80 .. 89 B 70 .. 79 C 60 .. 69 D 0 .. 59 F otherwise F
Nested if statements (Cont.)
- Most C# programmers prefer to use else if:
if ( grade >= 90 ) Console.WriteLine( "A" ); else if ( grade >= 80 ) Console.WriteLine( "B" ); else if ( grade >= 70 ) Console.WriteLine( "C" ); else if ( grade >= 60 ) Console.WriteLine( "D" ); else Console.WriteLine( "F" );
16
Short-circuit Evaluation
- Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far.
- Rule: Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) { Console.WriteLine("low average"); }
- In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated.
- In this way, we avoid “division by zero” error (that would cause to stop the execution of the program)
- Alternative method to avoid division by zero without using short-circuit evaluation:
if (count != 0) { if (scores/count < 60) { Console.WriteLine("low average"); } }
Solution to Dangling Else
Problem
if ( x % 2 == 0) { if ( x < 0 ) Console.WriteLine("{0} is an even, negative number“, x); } else { Console.WriteLine("{0} is an odd number“, x); }
• Now else belongs to the first if
• if – else matching rule
- Each else belongs to the nearest if for which there is no else and in the same compound block
switch statement
• The switch multiple-selection statement
performs different actions based on the
value of an expression.
• Each action is associated with the value of a
constant integral expression or a constant
string expression that the expression may
assume.
• Let’s see an example: GradeBookswitch.cs