Presentation is loading. Please wait.

Presentation is loading. Please wait.

Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 12-10-1429.

Similar presentations


Presentation on theme: "Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 12-10-1429."— Presentation transcript:

1 Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 12-10-1429

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

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

4 Simple Logic Expression C. Example let a = 17 and b = 42  (a < b) is true  (a > b) is false  (a <= b) is true  (a >= b) is false  (a == b) is false  (a != b) is true 4 1

5 Complex Logic Expression A. Introduction  can combine expressions to get complex logical expressions  useful for more realistic data comparison tasks B. Prototype 5 2 Imagine 1 light with 2 switches; the operator between them is &&, ||, or ! Logic ExpressionResult TRUE && TRUETRUE TRUE && FALSEFALSE FALSE && TRUEFALSE FALSE && FALSEFALSE Logic ExpressionResult TRUE || TRUETRUE TRUE || FALSETRUE FALSE || TRUETRUE FALSE || FALSEFALSE Logic ExpressionResult ! TRUEFALSE ! FALSETRUE AND && OR || NOT !

6 Complex Logic Expression C. Example let x = 3.14 and y = 7.89  ((x < 4)&&(y < 8)) is true (because both halves are true)  ((x > 3)&&(y > 8)) is false (because second half is false)  ((x 8)) is true (because first half is true)  ((x < 3)||(y < 8)) is true (because second half is true)  ((x > 4)||(y > 8)) is false (because both halves are false)  (x < y) is true, !(x < y) is false  (x >= y) is false, !(x >= y) is true  (a == b) is false, !(a == b) is true  (a != b) is true, !(a != b) is false 6 2

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

8 Conditional Statements A. Overview  control the flow of your program  two types of the conditional statements available in C:  if statement  Switch statement 8 4

9 IF Statement A. Overview  control the flow of your program  based on True or False  allow selecting an action based on condition  three types of the IF statements: 1. IF (allows the flow of the program to be changed) 2. IF-ELSE (gives an alternative path to be executed if the IF statement condition is False) 3. Nested IF (you will see a group of IF statements that each checks one condition within another) 9 4a

10 IF Statement (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  you only need semi-colon after single statements, not after { } 10 4a1 1 2 3 Condition 5 6 7 4 T

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

12 C. Example scanf(“%d”, &a); scanf(“%d”, &b); if (b > a) printf ("B is larger than A\n“); printf (“Done...\n“); scanf(“%d”, &a); scanf(“%d”, &b); if (a < b) { printf("A is smaller than B\n“); printf("The difference is %d\n“, b–a); } printf (“Done...\n“); 1. 2. 3. 4. 5. 6. 1. 2. 3. 4. 5. IF Statement (IF) 12 4a1 In a diagram, you can merge the sequential blocks in one block 1-2 3 5 4 T 3 6 4-5 T

13 IF Statement (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 13 4a2 1 2 3 Condition 6 7 8 5 T 4 F

14 IF Statement (IF-ELSE) B. Prototype if ( condition 1 ) { // A. Execute these statements // if condition 1 is TRUE } else if ( condition 2 ) { // B. Execute these statements // if condition 2 is TRUE } 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 } 14 4a2 The compiler looks at the entire program in one line unless there is ; The same Cond.1 A T F Cond.2 B T F Cond.3 C T F D

15 C. Example printf(“Enter the grade for the course: ”); scanf(“%d”, &grade); if (grade >= 90) printf(“GPA = A\n”); else if (grade >= 80) printf(“GPA = B\n”); else if (grade >= 70) printf(“GPA = C\n”); else if (grade >= 60) printf(“GPA = D\n”); else { printf(“GPA = F\n”); printf(“ UNSATISFACTORY.\n”); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. IF Statement (IF-ELSE) 15 4a2 ELSE is not an stand alone statement, so do not put a line number for it

16 IF Statement (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 16 4a3

17 IF Statement (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 } } 17 4a3 Exp. 1 A T E F Exp. 2 B T C F Exp. 3 D T Exp. 4 F T

18 C. Example if (a > 0) { if (b < 0) { a = 3 * b; c = a + b; } } else { a = 2 * a; c = b / a; } 1. 2. 3. 4. 5. 6. IF Statement (Nested IF) 18 4a3 Draw the flowchart for this program?

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

20 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1  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 -20-

21 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1  Input  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  Output  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 -21-

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

23 Implementation Problem Analysis Design Outline Testing Maintenance #include int main(void) { int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // 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); } ATM Simulation 1 P1 -23- 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.

24 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 #include int main(void) { int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance /* 1. Initial the balance */ balance = 0; /* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command); if (command == 1) /* 2.1 Deposit Money */ { printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; } else if (command == 2) /* 2.2 Withdraw Money */ { printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; } else if (command == 3) /* 2.3 Print Balance */ { printf("Current balance = %d\n", balance); } return(0); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. P1 -24-

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

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

27 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 #include int main(void) { int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance /* 1. Initial the balance */ balance = 0; /* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command); if (command == 1) /* 2.1 Deposit Money */ { printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; } else if (command == 2) /* 2.2 Withdraw Money */ { printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; } else if (command == 3) /* 2.3 Print Balance */ { printf("Current balance = %d\n", balance); } else /* Otherwise, display an error */ { printf("Error choice...\n"); } return(0); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. P1 -27-

28 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 1 P1 -28-

29 Switch Statement A. Introduction  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 B. Prototype switch ( decision value ) { case label1 : statements; break; case label2: statements; break; default: statements; } 29 4b

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

31 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2  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 -31-

32 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2  Input  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  Output  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 -32-

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

34 Implementation Problem Analysis Design Outline Testing Maintenance #include int main(void) { int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // 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); } ATM Simulation 2 P2 -34- 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23.

35 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 #include int main(void) { int command; // Input: an option from the main menu int money; // Input: withdraw or deposite money int balance; // Output: Display the balance /* 1. Initial the balance */ balance = 0; /* 2. Ask the user to choose one of the 3 options */ printf(" Main Menu\n"); printf("-----------------------\n"); printf(" 1 - Deposit money\n"); printf(" 2 - Withdraw money\n"); printf(" 3 - Print balance\n"); printf("Enter command number: "); scanf("%d", &command); switch (command) { case 1: /* 2.1 Deposit Money */ printf("Enter deposit amount: "); scanf("%d", &money); balance = balance + money; break; case 2: /* 2.2 Withdraw Money */ printf("Enter withdraw amount: "); scanf("%d", &money); balance = balance - money; break; case 3: /* 2.3 Print Balance */ printf("Current balance = %d\n", balance); break; default: /* Otherwise, Error Message */ printf("Error choice...\n"); } return(0); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. P2 -35-

36 Implementation Problem Analysis Design Outline Testing Maintenance ATM Simulation 2 P2 -36-

37 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”); 37 5 Make sure to indent the block of statements to clear the readability

38 Evaluation Homework 1. 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? 2. The result of the following logic expression is: flag || !(y + z >= x – z) where (flag=0; x=3; y=4; z=2) A. True B. False 3. The output of the following flow diagram if (X=1) is: A. 1 B. 2 C. 3 D. 13 E. 23 -38- hw X>2 printf(“2”);printf(“1”); printf(“3”); TF

39 Evaluation Homework 4. 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) 5. Re-write the following program them after fixing the errors? Show the output and draw the flow diagram? -39- hw 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 = %f\n”, speed, fee(speed)); } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

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


Download ppt "Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS 202 12-10-1429."

Similar presentations


Ads by Google