Lecture 8 if and switch Statements Daily Puzzle If a bottle, partly filled with liquid, has a round, square or rectangular bottom which is flat, can you find its volume using only a ruler? You may not add or pour out liquid.
Daily Puzzle Solution: area of base (h 1 +h 2 ) Announcements Assignment sheet error- no two player mode for mugwump Assignment hint sheets posted on website Assignment grading will be the week AFTER the due date - TAs do the grading (not instructors) - will be able to start booking times after the break Next week's labs are a practise lab exam - Monday and Tuesday people can go to other lab times or to extra lab times (will be posted)
Announcements Prof. McCuaig has several raspberry pi kits still and any student who needs one may purchase one today between 2:30 and 4:30 in her office (Reynolds 311) Q&A Do you have a question? (I may have an answer)
if statements What happens here? a = -12; if (a > 0) printf( a is positive\n ); b = log(a); if statements If a is greater than 0, it prints a is positive. It calculates the log of a regardless of the outcome of the if statement.
if statements To fix this, use a compound statement! a = -12; if (a > 0) { printf( a is positive\n ); b = log(a); if statements NOTE: No semicolons after the curly braces!
if-else statements No Is the condition true? Yes if-else statements The simplest possible if-else statement takes the form:! if (expression)!!! statement1;!!! else!!! statement2;
if-else statements statement1 is executed if expression has a nonzero value. If expression has a value of zero, the statement2 is executed. if-else example #include <stdio.h> int main(void) { int a_number; printf( Enter a number: ); scanf( %d, &a_number); if (a_number % 2 == 0) printf( %d is even\n, a_number); else printf( %d is odd\n, a_number); return 0;
if-else statements There are *many* different combinations: if (expression) if (expression){ statement1; statement1a; else { statement1b; statement2a; statement2b; else statement2; if-else statements For example:!! if (x < y)!! min = x;!! else!! min = y; If x < y is true, then min is assigned the value of x; if it is false, min is assigned the value of y.
if-else statements For example: if (denominator == 0.00)!! printf( Divide by zero );! else!! f = numerator/denominator; if-else statements If the value of the variable denominator is less than zero, an error message is printed otherwise the value of f is computed.
if-else statements /* Find the minimum of two values */ #include <stdio.h> int main(void) { int x, y, min; printf( Input two integers: ); scanf( %d%d, &x, &y); if (x < y) min = x; else min = y; printf( The minimum value is %d\n, min); return 0; if-else statements An example of a syntax error:! if ( a!= b) {! a = a + 1;! b = b + 1;! ;! else! c = a + b;
if-else statements The syntax error occurs because the semicolon following the right brace creates an empty statement, and consequently the else has nowhere to attach! dangling else There is an ambiguity when an else is omitted from a nested if statement. This is the dangling else problem.! if (n > 0)! if (a > b)!! c = a;! else!! c = b;
dangling else For example consider a conditional statement to calculate shipping charges: 1. To ship a 1 lb packet within Canada, the cost is $5, except for Yukon. To ship to Yukon (which is very remote), the cost $10. 2. To ship a 1 lb packet outside Canada, the cost is $20 dangling else The following is an if-statement that computes the shippingcharge : double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00;
dangling else Can be syntactically interpreted in two ways: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; = ambiguity dangling else C interprets it the following way: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00;
dangling else C associates the else with the closest previous else-less if. dangling else If that s not what you want, use braces to force the proper association.! if (n > 0) {! if (a > b)!! c = a;!! else!! c = b;
dangling else C interprets it the following way: double shippingcharge; shippingcharge = 5.00; if ( country == "CANADA") { if ( province == "YT" ) shippingcharge = 10.00; else shippingcharge = 20.00; dangling else /* Find the maximum of three real values */ #include <stdio.h> int main(void) { double x, y, z, max; printf( Input three real numbers: ); scanf( %lf%lf%lf, &x, &y, &z); if (x > y) if (x > z) max = x; else max = z; else if ( y < z) max = z; else max = y; printf( The maximum value is %f\n, max); return 0;
nested if Sometimes the if-else statement is used for a multi-way decision. The expressions are evaluated in order; if any expression is true, the statement associated with it is executed, and this statement terminates the whole chain. nested if The last else can be used to handle the default case where none of the other conditions is satisfied.
nested if if (expression1) statement1; else if (expression2) statement2; else if (expression3) statement3;... else statementn; nested if int posn=0, negn=0, zeron=0; if (x > 0) posn = posn + 1; else if (x < 0) negn = negn + 1; else zeron = zeron + 1;
nested if if (score == 100) printf( Superb\n ); else if (score >= 90) printf( Excellent\n ); else if (score >= 80) printf( Very good\n ); else if (score >= 70) printf( Good\n ); else if (score >= 60) printf( Satisfactory\n ); else if (score >= 50) printf( Pass\n ); else printf( Fail\n ); what happens here? In mathematics the expression 2<k<7 means that k is greater than 2, and less than 7. int k = 8; if (2 < k < 7) printf( true ); else printf( false );
what happens here? true is always printed. Why? 2 < k < 7 is equivalent to (2 < k) < 7 Because 2 < k is true, its value is 1. Therefore 2 < k < 7 is equivalent to 1 < 7 Which is obviously true. what happens here? The correct way to write a test is: 2 < k && k < 7 which is equivalent to: ((2 < k) && (k < 7))
switch statements The switch statement is a multiway conditional statement generalizing the ifelse statement. It is a far neater way of writing multiple if statements. switch statements The switch statement evaluates the value of an expression and branches to one of the case labels. Duplicate labels are not allowed, so only one case will be selected. The expression must evaluate an integer, or character.
switch statements Is condition 1 true? no yes break Is condition 2 true? no yes break default switch statements switch (expression){ case label1: statement1; case label2: statement2;... case labeln: statementn; default: default_statement;
switch statements The case labels can be in any order and must be integers. switch statements How does it work? Evaluate a switch expression. Go to the case label having a value that matches the value of the expression found in step 1.
switch statements If a match is not found, go to the default label; if there is no default label, terminate the switch. Terminate the switch when a break is encountered or by falling off the end. default label The default label can be put anywhere in the switch. When C sees a switch statement, it evaluates the expression and then looks for a matching case label. If none is found, the default label is used.
default label There may be at most one default label in a switch. Typically, it occurs last although it can occur anywhere. break statement A break statement inside a switch means that execution will continue after the switch statement. If a break statement is not there, execution falls through to the next statement.
break statement switch (expression){ case label1: statement1; break; case label2: statement2; break;... case labeln: statementn; break; default: default_statement; break statement The break statement interrupts the normal flow of control. switch (x) { case 1: x = x + 1; case 2: x = x + 2; break; // exit switch statement case 3: x = x + 3; default: x = 0; // break jumps to here
falling through At the end of the first case, there is no break, so the program falls through. Therefore, when x=1, the following statements will be executed: x = x + 1;! x = x + 2; falling through End every case in a switch with a break or the comment //Fall through switch (x) { case 1: x = x + 1; // Fall through case 2: x = x + 2; break; // exit switch statement case 3: x = x + 3; // Fall through default: x = 0;
if switch int x, y, r; if (y == 1) r = x; else if (y == 2) r = x * x; else if (y == 3) r = x * x * x; else printf( not a valid calculation ); if switch int x, y, r; switch (y) { case 1 : r = x; break; case 2 : r = x * x; break; case 3 : r = x * x * x; break; default : printf( not a valid calculation );
not always switch 52 lines of case statements switch (score) { case 100 : printf( Superb\n ); break; case 99 : ; case 98 : ;... case 90 : printf( Excellent\n ); break;... case 59 : ; case 58 : ;... case 50 : printf( Pass\n ); break; default : printf( Fail\n ); Sometimes switch is not the most appropriate structure Case study: quadratic
Case study: quadratic Input: a, b, c will cause a divide by zero error true if a = 0? false calculate Case study: quadratic if (a == 0) printf( Error: DIV by zero\n"); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d));
Case study: quadratic Input: a, b, c true if a = 0? false calculate false if b = 0? true calculate trivial case no roots ➊ further processing 1 root Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); // more calculations
Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); // more calculations Case study: quadratic calculate calculate 2 complex roots true if D < 0? false calculate single real root true if D = 0? false calculate 2 real roots
Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); if (D < 0){ // roots are complex if (D == 0){ // roots are real and equal if (D > 0){ // roots are real Case study: quadratic if (a == 0) if (b == 0){ printf( Sorry, no roots\n"); else { x = -c / b; printf("linear equation: root = %.2f\n", x); else { A = 2 * a; D = b * b - 4 * a * c; S = sqrt(fabs(d)); if (D < 0){ // roots are complex else if (D == 0){ // single real root else { // roots are real
Case study: quadratic if (D < 0){ xr = -b / A; xi = S / A; printf("complex roots: root1 = %.2f+%.2fi\n", xr, xi); printf(" root2 = %.2f-%.2fi\n", xr, xi); else if (D == 0){ x = -b / A; printf("single root = %.2f\n", x); else { x1 = (-b + S) / A; x2 = (-b + S) / A; printf("real roots: root1 = %.2f\n", x1); printf(" root2 = %.2f\n", x2);