If/ese & switch Unit 3 Sections 4.1-6, 4.8-12, 4.14-15 CS 1428 Spring 2018 Ji Seaman Straight-ine code (or IPO: Input-Process-Output) So far a of our programs have foowed this basic format: Input some vaues Do some computations Output the resuts The statements are executed in a sequence, first to ast. 1 2 Decisions Sometimes we want to be abe to decide which of two statements to execute: N fee is 2.9% monthy saes > $3,000 Y fee is 2.5% Reationa Expressions Making decisions require being abe to ask Yes or No questions. Reationa expressions aow us to do this. Reationa expressions evauate to true or fase. Aso caed: ogica expressions conditiona expressions booean expressions 3 4
Reationa Expressions 4.1 Reationa Operators Booean iteras: Binary operators used to compare expressions: true fase true evauates to true Booean variabes fase evauates to fase < Less than <= Less than or equa to > Greater than >= Greater than or equa to == Equas (note: do not use =)!! boo ispositive = true; boo found = fase;!= Not Equas ispositive evauates to true found evauates to fase 5 6 Reationa Expressions Reationa Operator Precedence Exampes: int x=6; int y=10; a. x == 5 evauates to fase b. 7 <= x + 2 evauates to c. y 3 > x evauates to d. x!= y evauates to d. true evauates to true Reationa operators are LOWER than arithmetic operators: int x, y; x < y -10 // minus happens first x * 5 >= y + 10 // mut, then pus, then >= Can assign reationa expressions to variabes: boo ispositive; int x; cin >> x; ispositive = x > 0; if the user types: 25 ispositive stores the vaue Reationa operators are HIGHER than assignment: int x, y; boo t1 = x > 7; // > then = boo t2 = x * 5 >= y + 10; // *, +, >=, = 7 8
4.2 The if statement The if statement can be used to execute a statement ony under certain conditions: if (expression) statement expression is evauated If it is true, then statement is executed. If it is fase, then statement is skipped if statement exampe Exampe: An empoyee gets a $100 bonus if their hours are over 40. doube rate = 14.50; doube hours, pay; cout << Enter the hours you worked: ; cin >> hours; pay = hours * rate; if (hours > 40) pay = pay + 100; cout << Your pay is: $ << pay << end; 9 10 4.3 The bock statement if with a bock a bock (or a compound statement) is a set of statements inside braces: { int x; cout << Enter a vaue for x: << end; cin >> x; cout << Thank you. << end; We can use a bock to conditionay execute more than just one statement: doube rate = 14.50; doube hours, pay; cout << Enter the hours you worked: ; cin >> hours; This groups severa statements into a singe statement. This aows us to use mutipe statements when by rue ony one is aowed. pay = hours * rate; if (hours > 40) { pay = pay + 100; cout << Your pay incudes a bonus. << end; cout << Your pay is: $ << pay << end; 11 12
4.4 The if/ese statement if-ese exampe if/ese statement is used to decide which of two statements to execute: if (expression) statement1 (or bock) ese statement2 (or bock) expression is evauated If it is true, then statement1 is executed. (statement2 is skipped). If it is fase, then statement2 is executed (statement1 is skipped). statement1 and statement2 are caed branches 13 doube monthysaes; doube price; doube rate; cout << "Enter monthy saes ast month: " ; cin >> monthysaes; cout << "Enter seing price of item: " ; cin >> price; if (monthysaes > 3000) rate =.025; ese rate =.029; doube commission = price * rate; cout << "Commission: $" << commission << end; Enter monthy saes ast month: 3025 Enter seing price of item: 100 Commission: $2.50 14 if-ese structure 4.5 Nested if statements Notice: if (monthysaes > 3000) rate =.025; ese rate =.029; reationa expression is in parentheses NO semi-coon after expression, nor the ese Good stye: indent the statements in each branch!! if-ese is a statement. It can occur as a branch of another if-ese statement. 15 16
Nested if statements Nested if statements if-ese is a statement. It can occur as a branch of another if-ese statement. char borninusa; int age; cout << Were you born in the USA (Y/N)?: ; cin >> borninusa; cout << Pease enter your age: ; cin >> age; if (borninusa == 'Y') if (age >= 35) cout << You quaify to run for President\n ; ese cout << You are too young to run for President\n ; ese cout << You must have been born in the US in order << to run for President << end; 17 if-ese is a statement. It can occur as a branch of another if-ese statement. char borninusa; int age; cout << Were you born in the USA (Y/N)?: ; cin >> borninusa; cout << Pease enter your age: ; cin >> age; if (borninusa == 'Y') if (age >= 35) cout << You quaify to run for President\n ; ese cout << You are too young to run for President\n ; ese cout << You must have been born in the US in order << to run for President << end; 18 Testing a series of conditions Common nested if pattern Decision structure to determine a grade 19 Determine etter grade from test score: If we are in this ese branch, what do we know about the vaue of testscore? if (testscore >= 90) grade = 'A'; ese { if (testscore >= 80) grade = 'B'; ese { if (testscore >= 70) grade = 'C'; ese { if (testscore >= 60) grade = 'D'; ese grade = 'F'; Note the braces are actuay optiona here! 20
4.6 The if/ese if Statement 4.8 Logica Operators Not reay a different statement, just a different way of indenting the nested if statement from the previous side: if (testscore >= 90) grade = 'A'; ese if (testscore >= 80) grade = 'B'; ese if (testscore >= 70) grade = 'C'; ese if (testscore >= 60) grade = 'D'; ese grade = 'F'; Used to create reationa expressions from other reationa expressions: && AND (binary operator) a && b is true ony when both a and b are true OR (binary operator)! a b is true whenever either a or b is true NOT (unary operator) removed braces, put if ( ) on previous ine!a is true when a is fase eiminated nested indentation. 21 22 Exampes int x=6; int y=10; Logica Operators a. x == 5 && y <= 3 fase && fase is fase b. x > 0 && x < 10 true && true is true c. x == 10 y == 10 fase true is true d. x == 10 x == 11 is e.!(x > 0)!true is f.!(x > 6 y == 10)!(fase true) is boo fag; fag = (x > 0 && x < 25); g.!fag h. fag x < 100 23 Logica Operator Precedence! is higher than most operators, so use parentheses: && is higher than int x;!(x < 0 && x > -10) // <, >, &&,! int x, y; boo fag; fag x * 5 >= y + 10 && x == 5 // which op is first? second? etc? && and are ower than arithmetic+reationa operators: parens not usuay needed 24
4.9 Checking Numeric Ranges We want to know if x is in the range from 1 to 10 (incusive) a. if (1 <= x <= 10) //as in math cass cout << YES << end; //THIS DOES NOT WORK IN C++: // ((1<=x) <=10) (assume x is -5) // => ( fase <= 10) // => ( 0<=10 ) is true, but shoud be fase b. if (1 <= x && x <= 10) cout << YES << end; -check: x=0? (1<=0 && 0<=10) => fase && true -check: x=5? (1<=5 && 5<=10) => true && true -check: x=100? (1<=100 && 100<=10) =>?? 25 4.10 Menus Menu-driven program: program controed by user seecting from a ist of actions Menu: ist of choices on the screen Dispay ist of numbered/ettered choices Prompt user to make a seection Test the seection in nested if/ese or switch Match found: execute corresponding code Ese: error message (invaid seection). 26 Sampe menu code 4.11 Vaidating User Input int choice; doube charges; int months = 12; // Dispay the menu and get a choice. cout << "Heath Cub Membership Menu\n\n"; cout << "1. Standard Adut Membership\n"; cout << "2. Chid Membership\n"; cout << "3. Senior Citizen Membership\n"; cout << "Enter your choice: "; cin >> choice; // Respond to the user's menu seection. if (choice==1) { charges = months * 40.0; cout << "The tota charges are $" << charges << end; ese if (choice==2) { charges = months * 20.0; cout << "The tota charges are $" << charges << end; ese if (choice==3) { charges = months * 30.0; cout << "The tota charges are $" << charges << end; ese { cout << ERROR: The vaid choices are 1 through 3. << end; 27 Input vaidation: inspecting input data to determine whether it is acceptabe Invaid input is an error that shoud be treated as an exceptiona case. The program can ask the user to re-enter the data The program can exit with an error message cout << Enter a positive number: ; cin >> x; if (x > 0) { //do something with x here ese { cout << You entered a negative number or 0. << end; cout << The program is ending. << end; 28
4.12 Comparing Characters and Strings Comparing string objects Characters are compared using their ASCII vaues A < B This is true. ASCII vaue of 'A' (65) is ess than the ASCII vaue of B (66) 1 < 2 This is true. ASCII vaue of '1' (49) is ess than the ASCI vaue of '2' (50) Like characters, strings are compared using their ASCII vaues string name1 = "Mary"; string name2 = "Mark"; name1 > name2 // true name1 <= name2 // fase name1!= name2 // true The characters in each string must match exacty in order to be equa Otherwise, use first nonequa character as basis of the comparison ( y > k ) Lowercase etters have higher ASCII codes than uppercase etters, so 'a' > 'Z' name1 < "Mary Jane" // true If a string is a prefix of the other, then it is ess than the other 29 30 4.14 The switch statement Like a nested if/ese, used to seect one of mutipe aternative code sections. tests one integer/char expression against mutipe constant integer/char vaues: switch (expression) { case const1: statements case constn: statements defaut: statements switch statement behavior switch (expression) { case const1: statements case constn: statements defaut: statements expression is evauated to an int/char vaue execution starts at the case abeed with that int/char vaue execution starts at defaut if the int/char vaue matches none of the case abes 31 32
switch statement syntax switch statement exampe switch (expression) { case const1: statements case constn: statements defaut: statements expression must have int/char type const1, constn must be constants! a itera or named constant statements is one or more statements (braces not needed and not recommended!) defaut: is optiona 33 Exampe: int quarter; switch (quarter) { case 1: cout << First ; case 2: cout << Second ; case 3: cout << Third ; case 4: cout << Fourth ; defaut: cout << Invaid choice ; 34 The break Statement Mutipe abes The break statement causes an immediate exit from the switch statement. if ch is a, it fas through to output Option A (then it breaks) Without a break statement, execution continues on to the next set of statements (the next case). Sometimes this is usefu: the textbook has some nice exampes. char ch; switch (ch) { case a : case A : cout << Option A ; case b : case B : cout << Option B ; case c : case C : cout << Option C ; defaut: cout << Invaid choice ; 35 36
4.15 More about bocks and scope The scope of a variabe is the part of the program where the variabe may be used. The scope of a variabe is the innermost bock in which it is defined, from the point of definition to the end of that bock. Note: the body of the main function is just one big bock. 37 Scope of variabes in bocks int main() { doube income; //scope of income is red + bue cout << "What is your annua income? "; cin >> income; if (income >= 35000) { int years; //scope of years is bue; cout << "How many years at current job? "; cin >> years; if (years > 5) cout << "You quaify.\n"; ese cout << "You do not quaify.\n"; Cannot access years ese down here cout << "You do not quaify.\n"; cout << Thanks for appying.\n ; return 0; 38 Variabes with the same name In an inner bock, a variabe is aowed to have the same name as a variabe in the outer bock. When in the inner bock, the outer variabe is not avaiabe (it is hidden). Not good stye: difficut to trace code and find bugs See exampe next side Variabes with the same name int main() { int number; cout << "Enter a number greater than 0: "; cin >> number; if (number > 0) { int number; // another variabe named number cout << "Now enter another number "; cin >> number; cout << "The second number you entered was "; cout << number << end; cout << "Your first number was " << number << end; 39 Enter a number greater than 0: 88 Now enter another number 2 The second number you entered was 2 Your first number was 88 40