Selection structures in C (II) H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 30, 2011) Washington State University.

Slides:



Advertisements
Similar presentations
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
Advertisements

CS 106 Introduction to Computer Science I 09 / 25 / 2006 Instructor: Michael Eckmann.
Arrays H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 13, 2011) Washington State University.
Recursion H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 21, 2011) Washington State University.
Modular Programming (2) H&K Chapter 6 Instructor – Gokcen Cilingir Cpt S 121 (July 8, 2011) Washington State University.
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
Strings (II) H&K Chapter 9 Instructor – Gokcen Cilingir Cpt S 121 (July 20, 2011) Washington State University.
Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University.
Structs H&K Chapter 11 Instructor – Gokcen Cilingir Cpt S 121 (July 18, 2011) Washington State University.
Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University.
Selection structures – logical expressions and if statements H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 28, 2011) Washington State University.
Arrays (III) H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 15, 2011) Washington State University.
Data Types H&K Chapter 7 Instructor – Gokcen Cilingir Cpt S 121 (July 12, 2011) Washington State University.
Arrays (II) H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 14, 2011) Washington State University.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
1. 2 Revision To understand the term Nesting –To be able to write programs that contain nested loops. –To be able to dry run programs containing nested.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
true (any other value but zero) false (zero) expression Statement 2
C++ for Engineers and Scientists Third Edition
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Chapter 4 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
(4-2) Selection Structures in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 16, 2015) Washington State University.
Flow of Control Part 1: Selection
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
(5-1) Selection Structures III in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 21, 2015) Washington State University.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
TK 1914 : C++ Programming Control Structures I (Selection)
(4-3) Selection Structures II in C H&K Chapter 4 Instructor - Andrew S. O’Fallon CptS 121 (September 18, 2015) Washington State University.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
(9-1) Strings I H&K Chapter 8 Instructor - Andrew S. O’Fallon CptS 121 (October 19, 2015) Washington State University.
(6-3) Modular Programming H&K Chapter 6 Instructor - Andrew S. O’Fallon CptS 121 (October 2, 2015) Washington State University.
(13-1) Exception Handling in C++ D & D Chapter 17 Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
(3-1) Functions II H&K Chapter 3 Instructor - Andrew S. O’Fallon CptS 121 (September 9, 2015) Washington State University.
(7-2) Arrays I H&K Chapter 7 Instructor - Andrew S. O’Fallon CptS 121 (October 9, 2015) Washington State University.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Decision Statements, Short- Circuit Evaluation, Errors.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
(6-2) Iteration in C II H&K Chapter 5 Instructor - Andrew S. O’Fallon CptS 121 (February 19, 2016) Washington State University.
Data Types H&K Chapter 7 Instructor - Andrew S. O’Fallon CptS 121 (March 4, 2016) Washington State University.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Discussion 4 eecs 183 Hannah Westra.
ECE Application Programming
Decisions Chapter 4.
Chapter 4 (Conditional Statements)
EGR 2261 Unit 4 Control Structures I: Selection
Decisions Given hours worked and pay rate, calculate total pay
Decisions Given hours worked and pay rate, calculate total pay
Writing a program with conditionals
Professor Jodi Neely-Ritz CGS3460
CSC215 Lecture Control Flow.
The Java switch Statement
EECE.2160 ECE Application Programming
CprE 185: Intro to Problem Solving (using C)
CSC215 Lecture Control Flow.
Presentation transcript:

Selection structures in C (II) H&K Chapter 4 Instructor – Gokcen Cilingir Cpt S 121 (June 30, 2011) Washington State University

You try it! What will be the output of the code below? int x = 0; if (x = 3) printf(“x is %d\n”, x); else printf(“x is %d\n”, x);

You try it! Explain the difference between the statements on the left and the statements on the right. What will x be in each situation given that its initial value was 1? if (x >= 0) x = x + 1; else if (x >= 1) x = x + 2; if (x >= 0) x = x + 1; if (x >= 1) x = x + 2;

C. Hundhausen, A. O’Fallon4 Nested if statements (1) Consider the following scenario: A high school baseball team awards merit points to players based on their offensive performance. A single (encoded 's') is worth 1 point, a double (encoded 'd') is worth 2 points, a triple (encoded 't') is worth 3 points, and a home run (encoded 'h') is worth 4 points. Any at-bat that leads to an out (encoded 'o') worth 0 points. Write a C statement that, given an at- bat character, properly awards points.

C. Hundhausen, A. O’Fallon5 Nested if statements (2) We can write a nested if statement to handle this situation: char at_bat; int points; printf("Enter the at-bat code (s,d,t,h,o): "); scanf(" %c",&at_bat); if (at_bat == 's') /* single */ { points = 1; } else if (at_bat == 'd') /* double */ { points = 2; } else if (at_bat == 't') /* triple */ { points = 3; } else if (at_bat == 'h') /* home run */ { points = 4; } else /* out */ { points = 0; }

C. Hundhausen, A. O’Fallon6 Nested if statements (3) Consider the following updated scenario: A high school baseball team awards merit points to players based on their offensive performance and the class standing ('f' = freshman, 'o' = sophomore, 'j' = junior, and 's' = senior). In particular, freshmen and sophomores earn an extra point for home runs, whereas juniors and seniors do not earn any points for singles. Write a C if-statement that, given an at- bat character and a class standing character, properly awards points.

C. Hundhausen, A. O’Fallon7 Nested if statements (4) We can write an even more nested if statements to handle this situation: char at_bat, class_standing; int points;... if (at_bat == 's') /* single */ { if (class_standing == 'f') || (class_standing == 'o') points = 1; else points = 0; } else if (at_bat == 'd') /* double */ { points = 2; } else if (at_bat == 't') /* triple */ { points = 3; } else if (at_bat == 'h') /* home run */ { if (class_standing == 'j') || (class_standing == 's') points = 4; else points = 5; } else /* out */ { points = 0; }

C. Hundhausen, A. O’Fallon8 Nested if statements (3) Nested if statements vs. compound conditionals ◦ Consider the following scenario: The National Weather Service would like to identify hourly weather reports in which the relative humidity is low (below 20%, the temperature is pleasant (between 75 and 85), and the winds are calm (0 to 10 m.p.h.). Assuming that the variables humidity, temp, and wind_speed hold those values, write an if statement that prints out a message when the conditions are met.

C. Hundhausen, A. O’Fallon9 Nested if statements (4) Nested if statements vs. compound conditionals (cont.) ◦ Alternative 1: Nested if if (humidity < 20) if (temp >= 75) if (temp <= 85) if (wind_speed <= 10) printf("Perfect conditions!\n"); ◦ Alternative 2: Compound if conditional if ((humidity = 75) && (temp <= 85) && (wind_speed <= 10)) printf("Perfect conditions!\n");

‘Dangling else’ problem To which if statement does the else belong to? if(y != 0 ) if (x != 0) result = x/y; else printf(“Error: y is equal to 0\n”);

C. Hundhausen, A. O’Fallon11 Nested if statements (5) Important to note that the C compiler always matches an else with the most recent incomplete if ◦ Example: if (humidity < 20) if (temp <= 32) printf("It's a cool, dry day.") if (wind < 10) printf("Luckily, the winds are calm."); else printf("The humidity is low, it's above freezing."); else if (humidity < 60) if (temp <= 32) printf("It's cold, with moderate humidity."); else printf("It's above freezing, with moderate humidity."); ◦ Do you see a problem here? How would you fix it?

C. Hundhausen, A. O’Fallon12 Nested if statements (6) Guidelines for using nested if statements ◦ Use braces to enclose all if branches, even if they contain only one statement  This will help you avoid the problem of mismatching if and else branches ◦ If possible, structure conditions so each alternative falls on false branch of previous condition (else if…) ◦ If each if branch contains a return statement, there's no need for an else clause, and you can avoid deep nesting ◦ In conditionals, don't mistake = for ==  The C compiler won't be able to catch this error, and you're condition will always evaluate to true!

C. Hundhausen, A. O’Fallon13 Nested if statements (7) Example: Nested if with return statements int get_points(char at_bat) { if (at_bat == 's') /* single */ return 1; /* assertion: at_bat != 's' */ if (at_bat == 'd') /* double */ return 2; /* assertion: at_bat != 's' && at_bat != 'd' */ if (at_bat == 't') /* triple */ return 3; /* assertion: at_bat != 's' && at_bat != 'd' && at_bat != 't' */ if (at_bat == 'h') /* home run */ return 4; /* assertion: at_bat != 's' && at_bat != 'd' && at_bat != 't' && at_bat != 'h' */ return 0; /* out */ }

C. Hundhausen, A. O’Fallon14 switch Statements (1) One issue with nested if statements is readability ◦ The deeper the nesting, the more difficult it can be to figure out what's happening Another issue is that the programmer could mistakenly "mis-nest" if statements, as in the previous example In cases in which the nesting is based on the value of a single variable, a switch statement may be a better alternative

C. Hundhausen, A. O’Fallon15 switch Statements (2) Let's revisit the previous baseball scenario: A high school baseball team awards merit points to players based on their offensive performance. A single (encoded 's') is worth 1 point, a double (encoded 'd') is worth 2 points, a triple (encoded 't') is worth 3 points, and a home run (encoded 'h') is worth 4 points. Any at- bat that leads to an out (encoded 'o') worth 0 points. Write a C statement that, given an at-bat character, properly awards points.

C. Hundhausen, A. O’Fallon16 switch Statements (3) The switch statement provides a cleaner way to handle this scenario: char at_bat; int points; points = 0; printf("Enter the at-bat code (s,d,t,h,o): "); scanf(" %c",&at_bat); switch (at_bat) { case 's': /* single */ points = points + 1; break; case 'd': /* double */ points = points + 2; break; case 't': /* triple */ points = points + 3; break; case 'h': /* home run */ points = points + 4; break; case 'o': points = points + 0; break; default: /* Anything but 's','d','t','h', 'o' */ printf("Unrecognized at-bat code."); break; } Don't forget to end each case with break Don't forget the begin and end curly braces If at_bat does not match any other case labels, the default case is executed

C. Hundhausen, A. O’Fallon17 switch Statements (4) What if we also want to allow capital letter codes? switch (at_bat) { case 's': /* single */ case 'S': points = points + 1; break; case 'd': /* double */ case 'D': points = points + 2; break; case 't': /* triple */ case 'T': points = points + 3; break; case 'h': /* home run */ case 'H': points = points + 4; break; case 'o': case 'O': points = points + 0; break; default: /* Anything but 's','d','t','h' */ printf("Unrecognized at-bat code."); break; } A single case can contain an arbitrary number of case labels

C. Hundhausen, A. O’Fallon18 switch Statements (5) Let's revisit the following scenario: A high school baseball team awards merit points to players based on their offensive performance and the class standing ('f' = freshman, 'o' = sophomore, 'j' = junior, and 's' = senior). In particular, freshmen and sophomores earn an extra point for home runs, whereas juniors and seniors do not earn any points for singles. Write a C if-statement that, given an at- bat character and a class standing character, properly awards points.

C. Hundhausen, A. O’Fallon19 switch Statements (6) We can write this more clearly as a switch statement with embedded if statements : switch (at_bat) { case 's': /* single */ if (class_standing == 'f') || (class_standing == 'o') points = 1; break; case 'd': /* double */ points = 2; break; case 't': /* triple */ points = 3; break; case 'h': /* home run */ if ((class_standing == 'f') || (class_standing == 'o')) points = 5; else points = 4; break; case 'o': points = 0; break; default: /* Anything but 's','d','t','h' */ printf("Unrecognized at-bat code."); break; }

C. Hundhausen, A. O’Fallon20 switch Statements (7) Notes on switch statements ◦ You can only switch based on a value of char or int. You cannot switch based on the value of a double. double era = 1.67; switch (era) { … /* can't do this */ An arbitrary number of statements can follow a case label It's a good idea always to define a default case A common mistake is to forget to end a case with break. If a break is forgotten, execution "falls" through to the next case label! (C can be cruel.)

21 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6 th Ed.), Addison- Wesley, 2010 P.J. Deitel & H.M. Deitel, C How to Program (5 th Ed.), Pearson Education, Inc., 2007.