Chapter 6 Branching 6.1 Branching (or Selection) 6.2 Relational and Logical Operators 6.3 The if Statement 6.4 The if-else Statement 6.5 The if-else if-else Statement 6.6 The Nested-if Statement 6.7 The switch Statement 6.8 The Conditional Operator
6.1 Branching (or Selection) Decision Decision Decision!!!! C statements are executed normally. Sometimes we need to tell the computer to do something only when some conditions are satisfied. This will alter the normal sequential execution. The if statement serves this purpose. Three forms: if statement if... else statement if... else if... else statement The switch statement provides a multi-way decision structure. We can choose one action out of a number of actions depending on some conditions.
6.2 Relational and Logical Operators Used for comparison between two values. Return boolean result: true or false. Relational Operators: operator example meaning == ch == a equal to!= f!= 0.0 not equal to < num < 10 less than <= num <=10 less than or equal to > f > -5.0 greater than >= f >= 0.0 greater than or equal to
Logical operators: Work on one or more relational expressions to yield a logical value: true or false. Allows testing results of comparison of expressions. operator example meaning!!(num < 0) not && (num1 > num2) && (num2 >num3) and (ch == \t ) (ch == ) or! returns true when the operand is false and returns false when the operand is true. && returns true when both operands are true otherwise it returns false. returns false when both operands are false otherwise it returns true.
list of operators of decreasing precedence:! not * / multiply and divide + - add and subtract < <= > >= less, less or equal, greater, greater or equal ==!= equal, not equal && logical and logical or The result of evaluating an expression involving relational and/or logical operators is either 1 or 0. When the result is true, it is 1. Otherwise it is 0, i.e. C uses 0 to represent a false condition.
/* example of the value of relational & logical expressions */ #include <stdio.h> main(void) { float logic_value; /* Numeric value of relational and logical expression */ printf("logic values of the following relations:\n"); logic_value = (3 > 5); printf("(3 > 5) is %f\n", logic_value); logic_value = (3 <= 5); printf("(3 <= 5) is %f\n", logic_value); logic_value = (15!= 3*5); printf("(15!= 3*5) is %f\n", logic_value); logic_value = (10 < 5) && (24 <= 15); printf("(10 < 5) && (24 <=15) is %f\n", logic_value);
} /* notice the portion: 24/0!!! */ logic_value = (10 < 5) && (24/0 <= 15); printf("(10 < 5) && (24/0 <=15) is %f\n", logic_value); logic_value = (36/6 > 2*3) (8 == 8); printf("(36/6 > 2*3) (8 == 8) is %f\n", logic_value); /* 36/0 == 0??? what s going on??? */ logic_value = (8 == 8) (36/0 == 0); printf("(8 == 8) (36/0 == 0) is %f\n", logic_value); $ex6_1 Logic values of the following relations: (3 > 5) is 0.000000 (3 <= 5) is 1.000000 (15!= 3*5) is 0.000000 (10 < 5) && (24 <=15) is 0.000000 (10 < 5) && (24/0 <=15) is 0.000000 (36/6 > 2*3) (8 == 8) is 1.000000 (8 == 8) (36/0 == 0) is 1.000000 $
In general, any integer expression whose value is non-zero is considered true; else it is false. For example: 3 is true, 0 is false 1 && 0 is false 1 0 is true!(5 >= 3) (1) is true scanf(...) returns the number of items read. It returns the value EOF, i.e. -1, when end of input is encountered. For example, scanf( %d %d, &n1, &n2); returns 2 if there is no error in the process of input
Flowcharts (from Chapter 2) Symbol Name Process Decision Input/Output Terminal Flowlines
6.3 The if Statement The format of the if statement: if (expression) statement; false expression true statement statement may be a single statement terminated by a semicolon or a compound statement enclosed by { }
#include <stdio.h> main(void) /* example of simple if statement */ { int num; /* Value supplied by user. */ printf("give me a number from 1 to 10 => "); scanf("%d",&num); if (num > 5) printf("your number is larger than 5.\n"); printf("%d was the number you entered.\n",num); return 0; } $./ex6_2 Give me a number from 1 to 10 => 3 3 was the number you entered. $./ex6_2 Give me a number from 1 to 10 => 7 Your number is larger than 5. 7 was the number you entered. $
6.4 The if-else Statement The format of the if... else statement is if (expression) statement1; else statement2; false true expression statement_2 statement_1 Both statement1 and statement2 may be single statements terminated by a semicolon or a compound statement enclosed by { }
/* This program computes the maximum of num1, num2 */ main(void) { int num1, num2, max; printf("enter two integers:"); scanf("%d %d", &num1, &num2); if (num1 > num2) max = num1; else max = num2; printf("the maximum is %d\n", max); } return 0; Start Read num1, num2 true false num1>num2? max=num1 max=num2 Print max End $./ex6_3 Enter two integers: 9 4 The maximum is 9 $ $./ex6_3 Enter two integers: -2 0 The maximum is 0 $
6.5 The if-else if-else Statement The format is if (expression1) statement1; else if (expression2) statement2; else statement3; true false expression1 true false statement1 expression2 statement2 statement3 Each of statement1, statement2 and statement3 may be a single statement terminated by a semicolon or a compound statement enclosed by { }
We may have as many else if in the if statement as we want (within the compiler limit): if (expression1) statement1; else if (expression2) statement2; else if (expression3) statement3;... else statementn; Statement i is executed when the first i-1 expressions are false and the ith expression is true.
/* an example of if... else if... else statements */ #include <stdio.h> main(void) { float temp; /* Temperature reading. */ printf("give me the temperature reading: "); scanf("%f",&temp); if ((temp >= 100.0) && ( temp <= 120.0)) printf("temperature OK, continue process.\n"); else if (temp < 100.0) printf("temperature too low, increase energy.\n"); else printf("temperature too high, decrease energy.\n"); return 0; } $./ex6_4 Give me the temperature reading: 105.0 Temperature OK, continue process. $./ex6_4 Give me the temperature reading: 130.0 Temperature too high, decrease energy.
The if-else if-else Statement Start if (mark <= 100 && mark >= 80) Read mark grade = 'A'; else if (mark < 80 && mark >= 70) T mark<=100 && mark>=80? F grade = 'B'; else if (mark < 70 && mark >= 60) grade = 'C'; grade='a' T mark<80 && mark>=70? F else grade = 'F'; grade='b' T mark<70 && mark>=60? F grade='c' grade='f' Print grade End
6.6 Nested-if Both the if branch and the else branch may contain if statement(s). The level of nested if statements can be as many as we want (up to the compiler limit). E.g. if (expression1) statement1; else if (expression2) else statement2; statement3; true statement1 expression1 true statement2 false expression2 false statement3
if (expression1) else if (expression2) statement1; else statement2; statement3; Nested true false expression1 true false expression2 statement3 statement1 statement2
Rule -> C compiler associates an else part with the nearest unresolved if. if (expression1) if (expression2) statement1; else statement2; statement1 - is executed when expression1 and expression2 are true. statement2 - is executed when expression1 is true and expression2 is false. When expression1 is false - neither statements are executed.
Example: Nested-if statements /* This program computes the maximum value of three numbers */ main(void) { int n1, n2, n3, max; printf("please enter three integers:"); Start scanf("%d %d %d", &n1, &n2, &n3); Read n1, n2, n3 if (n1 >= n2) true false if (n1 >= n3) n1>=n2 max = n1;? true false true else max = n3; n1>=n3 n2>=n3 else if (n2 >= n3)?? max = n2; max=n1 max=n3 max=n2 else max = n3; printf("the maximum of the three is %d\n", max); return 0; Print max } End false max=n3
$./ex6_5 Please enter three integers: 1 2 3 The maximum of the three is 3 $./ex6_5 Please enter three integers: 1 3 2 The maximum of the three is 3 $./ex6_5 Please enter three integers: 3 1 2 The maximum of the three is 3 $./ex6_5 Please enter three integers: 2 1 3 The maximum of the three is 3 $
6.7 The switch Statement switch (expression) { } case constant1: statement1; break; case constant2: statement2; break; case constantn: statementn; break; default: The syntax of a switch statement is statementd; expression constant1? true statement1 break false constant2? true statement2 break false constant3? true statement3 break false statementd
switch, case, break and default are reserved words. the result of expression in ( ) must be integral type constant1, constant2,... are called labels. Each must be an integer constant, a character constant or an integer constant expression, e.g. 3, 'A', 4+'b', 5+7,... etc. each of the labels constant1, constant2,... must deliver unique integer value. Duplicates are not allowed.
#include <stdio.h> main(void) { Example ex6_6.c - Using Switch statement char selection; /* Item to be selected by the user */ printf("select the form of Ohm's law needed by letter:\n"); printf("a] Voltage; B] Current; C] Resistance;\n"); printf("your selection (A, B, or C) => "); scanf("%c", &selection); switch (selection) { case 'A' : printf("v = I * R\n"); break; case 'B' : printf("i = V / R\n"); break; case 'C' : printf("r = V / I\n"); break; default : printf("that was not one of the proper selections.\n"); } /* End of switch. */ return 0; } Menu
$./ex6_6 Select the form of Ohm's law needed by letter: A] Voltage; B] Current; C] Resistance; Your selection (A, B, or C) => A V = I * R $./ex6_6... Your selection (A, B, or C) => B I = V / R $./ex6_6... Your selection (A, B, or C) => C R = V / I $./ex6_6... Your selection (A, B, or C) => D That was not one of the proper selections. $
#include <stdio.h> /* Menu-driven application */ main(void) { we may have multiple labels for a statement, for example, to allow both the lower and upper case selection in the previous example, we do this: char selection; /* Item to be selected by the user */ printf("select the form of Ohm's law needed by letter:\n"); printf("a] Voltage; B] Current; C] Resistance;\n"); printf("your selection (A, B, or C) => "); scanf("%c",&selection); switch (selection) { case a : case 'A' : printf("v = I * R\n"); break; case b : case 'B' : printf("i = V / R\n"); break; Menu
} case c : case 'C' : printf("r = V / I\n"); break; default : printf("that was not one of the \ proper selections.\n"); } /* End of switch. */ return 0; if we do not use break after some statements in the switch statement, execution will continue with the statements for the subsequent labels until a break statement or the end of switch statement. This is called fall through situation.
#include <stdio.h> main(void) { char selection; /* User input selection. */... printf("your selection => "); scanf("%c", &selection); switch(selection) { case 'A' : printf("rt = R1 + R2 + R3\n"); case 'B' : printf("it = Vt / Rt\n"); case 'C' : printf("pt = Vt * It\n"); break; default : printf("that was not a correct selection!"); } /* End of switch. */ return 0; }
$./ex6_7... Your selection => A /* fall through */ Rt = R1 + R2 + R3 It = Vt / Rt Pt = Vt * It $./ex6_7... Your selection => B /* fall through */ $./ex65_7... Your selection => C Pt = Vt * It $./ex6_7... Your selection => D That was not a correct selection! $ It = Vt / Rt Pt = Vt * It
Another Example: switch(choice) { case 'a': case 'A': result = num1 + num2; printf("%d + %d = %d\n", num1,num2,result); case 's': case 'S': result = num1 - num2; printf("%d - %d = %d\n", num1,num2,result); case 'm': case 'M': result = num1 * num2; printf("%d1 * %d = %d\n",num1,num2,result); break; default: printf("not the proper choices.\n"); }
Start Read choice, num1, num2 choice case 'A' or 'a'? true result=num1+num2 Print result false case 'S' or 's'? true result=num1-num2 false case 'M' or 'm'? true false Print error message Print result result=num1*num2 Print result break Start
6.8 The Conditional Operator The conditional operator is used in the following way: expression_1? expression_2 : expression_3 The value of this expression depends on whether expression_1 is true or false. If expression_1 is true, then the value of the expression is that of expression_2 otherwise it is expression_3.
Example ex6_8.c: conditional expressions #include <stdio.h> main(void) { float led_voltage; /* Voltage across LED (all in V) */ float resistor_voltage; /* Voltage across resistor */ float source_voltage; /* Voltage of source */ float circuit_current; /* Current in the LED (A) */ float resistor_value; /* Value of resistor in ohms */ printf("enter the source voltage in volts => "); scanf("%f", &source_voltage); printf("enter value of resistor in ohms => "); scanf("%f", &resistor_value); led_voltage = (source_voltage < 2.3)? source_voltage : 2.3;
resistor_voltage = source_voltage - led_voltage; circuit_current = resistor_voltage / resistor_value; printf("total circuit current is %f amperes.\n", circuit_current); } return 0; $./ex6_8 Enter the source voltage in volts => 2 Enter value of resistor in ohms => 50 Total circuit current is 0.000000 amperes. $./ex6_8 Enter the source voltage in volts => 5 Enter value of resistor in ohms => 27 Total circuit current is 0.100000 amperes. $
/* example ex6_9.c: a conditional expression */ #include <stdio.h> main(void) { int selection; /* User input selection */ printf("enter a 1 or a 0 => "); scanf("%d",&selection); selection? printf("a one.\n") : printf("a zero.\n"); } return 0; $./ex6_9 Enter a 1 or a 0 => 1 A one. $./ex6_9 Enter a 1 or a 0 => 0 A zero. $