Problem Solving and Program Design in C 5

Problem Solving and Program Design in C (5 th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 1431/1432 – Term 1

# CHAPTER 4 - Conditional Statements 1. 2. 3. 4. Simple Logic Expression Complex Logic Expression Evaluation Tree Conditional Statements 1. 2. ATM Simulation 1 ATM Simulation 2 IF Statement b) Switch Statement a) 5. Common Errors in Conditions column shows the topics index. column shows the programs index. -2 -

1 Simple Logic Expression A. Introduction B. often need to look at data values and make choices logical expressions are true/false statements of data relationships Prototype variables or constants relational or equality data Simple Logic Expression operator Operator variables or constants data Simple Logic Expression Operator Less than < Larger than or equal >= Larger than > Equal == Less than or equal <= Not equal != 3

1 Simple Logic Expression C. Example let a = 17 and b = 42 (a < b) True (a > b) False (a <= b) True (a >= b) False (a == b) False (a != b) True Statement has ! may confuse you, so read it without ! and flip the result 4

2 Complex Logic Expression A. Introduction B. combining more than one simple logic expressions make it a complex logical expression Prototype expression operator expression AND && OR || NOT ! Logic Expression Result TRUE && TRUE || TRUE ! TRUE FALSE TRUE && FALSE TRUE || FALSE TRUE ! FALSE TRUE FALSE && TRUE FALSE || FALSE && FALSE Imagine 1 light with 2 switches; the operator between them is &&, ||, or ! 5

2 Complex Logic Expression C. Example let x = 3. 14 and y = 7. 89 ((x < 4)&&(y < 8)) true) ((x > 3)&&(y > 8)) false) ((x < 4)||(y > 8)) ((x < 3)||(y < 8)) ((x > 4)||(y > 8)) false) !(x < y) False !(x >= y) True C. !(a == b) True D. !(a != b) False True (both halves are False (second half is True (first half is true) True (second half is true) False (both halves are 6

3 Evaluation Tree (Step-by-Step) A. Introduction B. Way to Do C. a way to solve a logic expression solve the simple logic expression first Example ((x < 5)&& !(y > 9)) 4 5 5 < (x=4 ; y=5) 9 > F T ! T && T 7

3 Evaluation Tree (Step-by-Step) A. Introduction B. Way to Do C. a way to solve a logic expression solve the simple logic expression first Example ((x < !(y. T > T 5)&& TRUE F 9)) (x=4 ; y=5) SECOND way 8

4 Conditional Statements A. Overview control the flow of your program based on True or False allow selecting an action based on condition two types of the conditional statements available in C: a. b. if statements Switch statements 9

4 a Conditional Statements – IF Statements A. Overview three types of the IF statements: 1. 2. 3. IF (allows the flow of the program to be changed if the IF statement condition is True) IF-ELSE (gives an alternative path to be executed if the IF statement condition is False) Nested IF (IF statements insides IF statements) 10

4 a 1 Conditional Statements – IF Statements (IF) A. Introduction can selectively execute code using if statement when logical expression is true, selected code is executed when logical expression is false, selected code is skipped selected code can be either a single statement or a block of statements which is enclosed in { } characters should indent code to aid program readability no need for semi-colon after IF statements 1 2 3 Condition T 4 5 6 7 11

4 a 1 Conditional Statements – IF Statements (IF) B. Prototype If you have only one statement after an if statement, you do not need to (but you can) put the statement in braces. For example: 2. if ( TRUE ) 3. Statement executes if condition is True 4. Statement executes if condition is True/False To have more than one statement execute after an if statement that evaluates to true, use braces. For example: 2. if ( TRUE ) 3. { All the statements in this block execute 4. if the condition is True 5. 6. } 1 2 T Condition 3 4 5 Statements between braces are called a compound statement, or a block 12

4 a 1 Conditional Statements – IF Statements (IF) C. Example 1. 2. 3. 4. 5. scanf(“%d”, &a); scanf(“%d”, &b); if (b > a) printf ("B is larger than An“); printf (“Done. . . n“); 1. 2. 3. 4. 5. 6. 7. 8. scanf(“%d”, &a); scanf(“%d”, &b); if (a < b) { printf("A is smaller than Bn“); printf("The difference is %dn“, b–a); } printf (“Done. . . n“); 1 -2 3 T 4 5 1 -2 3 T 5 -6 8 In a diagram, you can merge the sequential statements in one block 13

4 a 2 Conditional Statements – IF Statements (IF-ELSE) A. Introduction often need two alternatives in an IF statement want to execute certain code if expression is true want to execute different code if expression is false the if-else statement lets you do this can use single statement or block of code for either part should indent code to aid program readability 1 2 F 3 T Condition 4 5 6 7 8 14

4 a 2 Conditional Statements – IF Statements (IF-ELSE) The same B. Prototype if ( condition 1 ) { // A. Execute these statements // if condition 1 is TRUE F } else if ( condition 2 ) F Cond. 3 { // B. Execute these statements // if condition 2 is TRUE D } else if ( condition 3 ) { // C. Execute these statements // if condition 3 is TRUE } else { // D. Execute these statements // if condition 1, 2 and 3 are FALSE } F Cond. 2 T Cond. 1 T T A B C The compiler looks at the entire program in one line unless there is ; 15

4 a 2 Conditional Statements – IF Statements (IF-ELSE) C. Example 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. printf(“Enter the grade for the course: ”); scanf(“%d”, &grade); if (grade >= 90) printf(“GPA = An”); else if (grade >= 80) printf(“GPA = Bn”); else if (grade >= 70) printf(“GPA = Cn”); else if (grade >= 60) printf(“GPA = Dn”); else { printf(“GPA = Fn”); printf(“UNSATISFACTORY. n”); } Quiz: draw the flow diagram for this segment? 16

4 a 3 Conditional Statements – IF Statements (Nested IF) A. Introduction often need to check one condition within another can nest if statements to accomplish this need to take care when matching up { } brackets use indentation to reflect nesting and aid readability 17

4 a 3 Conditional Statements – IF Statements (Nested IF) B. Prototype if (expression 1) { // A. statements if (expression 2) { // B. statements } else { // C. statements if (expression 3) { // D. statements } } } else { // E. statements if (expression 4) { // F. statements } } F Exp. 1 T E Exp. 4 A F T F Exp. 2 T C Exp. 3 B T D 18

4 a 3 Conditional Statements – IF Statements (Nested IF) How many PATHs you have? 1) 1, 3, 5, 8 2) 1, 3, 5, 7, 9, 10 3) 1, 3, 5, 7, 9 4) 1, 2, 4, 6 5) 1, 2, 4 F 1 T 3 2 4 F T 6 5 T 7 9 8 T 10 19

4 a 3 Conditional Statements – IF Statements (Nested IF) C. Example 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } Quiz: draw the flow diagram for this segment? 20

4 a Conditional Statements – IF Statement B. Conclusion 1 1 1 2 2 2 3 Condition T F 3 4 Condition 4 T 3 5 4 5 6 7 6 7 Sequential IF IF / ELSE In a diagram, you can merge the sequential blocks in one block 21

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 Write a program that simulates an ATM, where they are three main options: 1. Deposit Money 2. Withdraw Money 3. Print Balance Assume the balance in the account is Zero Use if to choose an option from the Main Menu -22 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 Input Output An option from the main menu Amount of money to deposit if the user choose option 1 Amount of money to withdraw if the user choose option 2 The balance if the user choose option 3 Formula Balance = Balance + Deposit if the user choose option 1 Balance = Balance – Withdraw if the user choose option 2 Think about the input/formula/output for each option in the main menu -23 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 1. 2. Initial the balance = 0 Ask the user to choose one of the 3 options command 1 Deposit Money A. Get the amount of money that wants to deposit money B. Calculate the balance = balance + money 2 Withdraw Money A. Get the amount of money that wants to deposit money B. Calculate the balance = balance - money 3 A. Display the balance -24 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. #include <stdio. h> int main(void) { int command; int money; int balance; // Input: an option from the main menu // Input: withdraw or deposite money // Output: Display the balance /* 1. Initial the balance */ /* 2. Ask the user to choose one of the 3 options */ if (command == 1) /* 2. 1 Deposit Money */ { } else if (command == 2) /* 2. 2 Withdraw Money */ { } else if (command == 3) /* 2. 3 Print Balance */ { } return(0); } -25 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 1. #include <stdio. h> 2. 3. int main(void) 4. { 5. int command; // Input: an option from the main menu 6. int money; // Input: withdraw or deposite money 7. int balance; // Output: Display the balance 8. 9. /* 1. Initial the balance */ 10. balance = 0; 11. 12. /* 2. Ask the user to choose one of the 3 options */ 13. printf(" Main Menun"); 14. printf("------------n"); 15. printf(" 1 - Deposit moneyn"); 16. printf(" 2 - Withdraw moneyn"); 17. printf(" 3 - Print balancen"); 18. printf("Enter command number: "); 19. scanf("%d", &command); 20. 21. if (command == 1) /* 2. 1 Deposit Money */ 22. { -2623. printf("Enter deposit amount: ");

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 Useless program because it doesn’t have a loop to see the new balance -27 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 Validation Check: If a user put an invalid input, you need to display an error message Maintain the program to validate the inputs? input has to be 1, 2, 3 only -28 -

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 1. #include <stdio. h> 2. 3. int main(void) 4. { int command; // Input: an option from the main menu 5. int money; // Input: withdraw or deposite money 6. int balance; // Output: Display the balance 7. 8. /* 1. Initial the balance */ 9. balance = 0; 10. 11. /* 2. Ask the user to choose one of the 3 options */ 12. printf(" Main Menun"); 13. printf("------------n"); 14. printf(" 1 - Deposit moneyn"); 15. printf(" 2 - Withdraw moneyn"); 16. printf(" 3 - Print balancen"); 17. printf("Enter command number: "); 18. scanf("%d", &command); 19. 20. if (command == 1) /* 2. 1 Deposit Money */ 21. { 22. -29 printf("Enter deposit amount: "); 23.

P 1 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 1 -30 -

4 b Conditional Statements – Switch Statement A. Introduction B. switch statement convenient for handling multiple if-else cases need to use single value as decision variable (called: controlling expression) of type: int or char, but not of type double need to identify code to be executed for each case it is essential to end each case with break command can use default for all cases not specifically labeled Prototype switch ( decision value ) { case label 1 : statements; break; case label 2: statements; break; default: statements; } 31

4 b Conditional Statements Switch Statement C. Examples 1. switch (command) 2. { 3. case 1: 4. printf(“Light is ON. n"); 5. break; 6. case 2: 7. printf(“Light is OFF. n"); 8. break; 9. default: 10. printf("Error Option!n"); 11. } F F 10 6 3 T 1. switch (command) 2. { 3. case 1: 4. printf(“Light is ON. n"); 5. break; 6. case 2: 7. printf(“Light is OFF. n"); 8. break; 9. default: 10. printf("Error Option!n"); 11. } F 4 T 7 F 10 6 3 T 4 T 7

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 Write a program that simulates an ATM, where they are three main options: 1. Deposit Money 2. Withdraw Money 3. Print Balance Assume the balance in the account is Zero Use if to choose an option from the Main Menu Validate the input; if a user choose a wrong option, display an error message As same as Program 1, but use Switch statement instead of IF -33 -

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 Input Output An option from the main menu Amount of money to deposit if the user choose option 1 Amount of money to withdraw if the user choose option 2 The balance if the user choose option 3 An error message if the user choose a wrong option Formula Balance = Balance + Deposit if the user choose option 1 Balance = Balance – Withdraw if the user choose option 2 Think about the input/formula/output for each option in the main menu -34 -

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 1. 2. Initial the balance = 0 Ask the user to choose one of the 3 options command 1 Deposit Money A. Get the amount of money that wants to deposit money B. Calculate the balance = balance + money 2 Withdraw Money A. Get the amount of money that wants to deposit money B. Calculate the balance = balance - money 3 Print Balance A. Display the balance Error Option A. Display an error message -35 -

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. #include <stdio. h> int main(void) { int command; int money; int balance; // Input: an option from the main menu // Input: withdraw or deposite money // Output: Display the balance /* 1. Initial the balance */ /* 2. Ask the user to choose one of the 3 options */ switch (command) { case 1: /* 2. 1 Deposit Money */ break; case 2: /* 2. 2 Withdraw Money */ break; case 3: /* 2. 3 Print Balance */ break; default: /* Otherwise, Error Message */ } return(0); } -36 -

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 1. #include <stdio. h> 2. 3. int main(void) 4. { int command; // Input: an option from the main menu 5. int money; // Input: withdraw or deposite money 6. int balance; // Output: Display the balance 7. 8. /* 1. Initial the balance */ 9. balance = 0; 10. 11. /* 2. Ask the user to choose one of the 3 options */ 12. printf(" Main Menun"); 13. printf("------------n"); 14. printf(" 1 - Deposit moneyn"); 15. printf(" 2 - Withdraw moneyn"); 16. printf(" 3 - Print balancen"); 17. printf("Enter command number: "); 18. scanf("%d", &command); 19. 20. switch (command) 21. { 22. -37 case 1: /* 2. 1 Deposit Money */ 23.

P 2 Problem Analysis Design Outline Implementation Testing Maintenance ATM Simulation 2 -38 -

5 Common Errors in Conditions A. if (0 <= x <= 4) printf(“Condition is true. n”); B. if (x = 10) printf(“x is 10. n”); C. if (x > 0) sum = sum + x; printf(“Greater than zero. n”); else printf(“Less than or equal to zero”); Make sure to indent the block of statements to clear the readability 39

hw Evaluation Homework 1. 2. The 2 nd example in IF-ELSE described transferring the number grades to letter grades. Write a program for this problem using a Switch statement without any IF statement? The result of the following logic expression is: where (flag=0; x=3; y=4; z=2) flag && !(y + z >= x – z) A. B. 3. True False The output of the following flow diagram if (X=1) is: A. B. C. D. E. 1 2 3 13 23 F printf(“ 1”); X>2 T printf(“ 2”); printf(“ 3”); -40 -

hw Evaluation Homework 4. 5. Type Program 2 and display the result when case = 2 (Print a copy of the code and a snapshot of the output) , and then remove the break from the second case. (Display the output only in the same page when case=2) Describe what happened when break was removed? (put the answer at the end of the same page) Re-write the following program them after fixing the errors? Show the output and draw the flow diagram? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. double fee(int speed) { IF (speed > 160) money = 300. 00; elseif (speed > 140) money = 200. 00; Else money = 100. 00; return (money); } int main(void) { printf(“What is the speed of the car: ”); scanf(“%d”, &speed); printf(“Speed = %d, Ticket = %fn”, speed, fee(speed)); } -41 -

# CHAPTER 4 - Conditional Statements 1. 2. 3. 4. Simple Logic Expression Complex Logic Expression Evaluation Tree Conditional Statements 1. 2. ATM Simulation 1 ATM Simulation 2 IF Statement b) Switch Statement a) 5. Common Errors in Conditions column shows the topics index. column shows the programs index. -42 -
- Slides: 42