50 likes | 182 Views
NQC: Control Structures: Branching Last updated 10/6/05 10:00am. References: Baum Chapter 3 pp. 50-52 NQC Tutorial pp. 14-15 Baum Appendix D pg 368. Conditions (Relational Operators) Recall the statement if(condition) { Body }
E N D
NQC: Control Structures: BranchingLast updated 10/6/05 10:00am References: Baum Chapter 3 pp. 50-52 NQC Tutorial pp. 14-15 Baum Appendix D pg 368.
Conditions (Relational Operators) Recall the statement if(condition) { Body } A condition is an expression which when evaluated has a value of true or false. if(SENSOR_1 == 1)…… // == is the equality operator if(SENSOR_1 != 1)…… // != is the not equality operator if(SENSOR_2 < 10)…… if(SENSOR_2 > 20)…… if(SENSOR_3 >= 25)…… If SENSOR_1 is a touch sensor, the first until statement will execute the body if SENSOR_1 has a value of 1. What do the other statements do?
Conditions (Logical Operators) Relational operators produce binary values true, false Suppose x has a value of 5, then the condition x>2 has a value of true x<3 has a value of false The operator && is the logical AND The operator || is the logical OR true && true is true true && false is false true || true is true true || false is true false || false is false What happens in these statements? if(SENSOR_1 >10 && SENSOR_1<20)… if (SENSOR_1 == 1 || SENSOR_2 ==1)…
Forms for the if If(condition) body; if(SENSOR_1 == 1) Off(OUT_A); ------------------------------------------------------------ if(SENSOR_1 == 1) Off(OUT_A); // this is the same as above What about this? if(SENSOR_1 == 1) Off(OUT_A); Off(OUT_B); // Indentation has no effect on execution; // In all cases, OUT_B will be turned off. What about this? if(SENSOR_1 == 1) // This will turn off both OUT_A and OUT_B { // only if SENSOR_1==1. Off(OUT_A); Off(OUT_B); }
Two forms for the if if(condition) ss1 if(condition) ss1 else ss2 ss1 statement or statements { } when condition is true. ss2 statement or statements { } when condition is false. ------------------------------ if(SENSOR_1==1) Off(OUT_A); else { OnRev(OUT_A); Off(OUT_B); } ---------------- This can also be written if(SENSOR_1==1)Off(OUT_A); else{OnRev(OUT_A);Off(OUT_B);} However, the first form is easier to read!