1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.

Slides:



Advertisements
Similar presentations
ICS103: Programming in C 4: Selection Structures Muhamed F. Mudawar.
Advertisements

Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
1 ICS103 Programming in C Ch4: Selection Structures.
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
true (any other value but zero) false (zero) expression Statement 2
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Topic 5 – Control Structures. CISC 105 – Topic 5 Program Flow Thus far, we have only encountered programs that flow sequentially. The first statement.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Logical Operators and Conditional statements
1 ICS103 Programming in C Lecture 6: Selection Structures.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Selection. Structured Components There are three basic constructs that can be used to build programs Sequence One statement follows another. Selection.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
True or False Unit 3 Lesson 7 Building Blocks of Decision Making With Additions & Modifications by Mr. Dave Clausen True or False.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
Decision Structures and Boolean Logic
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
ICT Introduction to Programming Chapter 4 – Control Structures I.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
chap4 Chapter 4 Selection Structures: if and switch Statements.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
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 Statements: Part1  if, if…else, switch 1.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
CHAPTER 5: SELECTION STRUCTURES: if and switch STATEMENTS Prepared By: Pn. Nik Maria Nik Mahamood Reference: Hanly, Koffman, C Problem Solving and Program.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Chapter 4 : Selection Structures: if and switch statement By Suraya Alias.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and If
Topics The if Statement The if-else Statement Comparing Strings
Topics The if Statement The if-else Statement Comparing Strings
Chapter 3: Program Statements
Chapter 8 JavaScript: Control Statements, Part 2
The System.exit() Method
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Chapter 4: Selection Structures: if and switch Statements
CprE 185: Intro to Problem Solving (using C)
ICS103: Programming in C 4: Selection Structures
Boolean Expressions September 1, 2019 ICS102: The course.
Presentation transcript:

1 CS 201 Selection Structures (1) Debzani Deb

2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable list place holder When accepting double values, the placeholder used in scanf function is %lf i.e. % then el then ef.

3 Overview Control Structures Conditions if statements Nested and Multiple if Statements

4 Control Structures Control structures –control the flow of execution in a program or function. Three basic control structures: Sequential Flow - this is written as a group of statements bracketed by { and }where one statement follows another. Selection control structure - this chooses between multiple statements to execute based on some condition. Repetition – this structure executes a block of code multiple times. C Y N C Y N

5 Compound Statements A Compound statement or a Code Block is written as a group of statements bracketed by { and } and is used to specify sequential flow. { Statement_1; Statement_2; Statement_3; }  Example: the main function is surrounded by {}, and its statements are executed sequentially.  Function body also uses compound statement.

6 Selection in C if Statement  Many form switch statement  Similar to case structure

7 Conditions A program chooses among alternative statements by testing the values of variables.  0 means false  Any non-zero integer means true, Usually, we’ll use 1 as true. if (a>=b) printf(“a is larger”); else printf(“b is larger”); Condition - an expression that establishes a criterion for either executing or skipping a group of statements  a>=b is a condition that determines which printf statement we execute.

8 Relational and Equality Operators Most conditions that we use to perform comparisons will have one of these forms:  variable relational-operator variable e.g. a < b  variable relational-operator constant e.g. a > 3  variable equality-operator variable e.g. a == b  variable equality-operator constant e.g. a != 10

9 Relational and Equality Operators OperatorMeaningType <less thanrelational >greater thanrelational <=less than or equal torelational >=greater than or equal torelational ==equal toequality !=not equal toequality

10 Logical Operators logical expressions - expressions that uses conditional statements and logical operators.  && (and) –A && B is true if and only if both A and B are true  || (or) –A || B is true if either A or B are true  ! (not) –!(condition) is true if condition is false, and false if condition is true –This is called the logical complement or negation Example  (salary 5)  (temperature > 90.0) && (humidity > 90)  !(temperature > 90.0)

11 Truth Table && Operator ABA && B False (zero) True (non-zero)False (zero) True (non-zero)False (zero) True (non-zero)

12 Truth Table || Operator ABA || B False (zero) True (non-zero) False (zero)True (non-zero)

13 Operator Table ! Operator A!A False (zero)True (non-zero) False (zero)

14 Remember! && operator yields a true result only when both its operands are true. || operator yields a false result only when both its operands are false.

15 Operator Precedence Operator’s precedence determine the order of execution. Use parenthesis to clarify the meaning of expression. Relational operator has higher precedence than the logical operators. Ex: followings are different. (x 0.0) x 0.0 function calls ! + - & (unary operations) *, /, % +, -, = ==, != && || =

16 Figure 4.1 Evaluation Tree and Step-by-Step Evaluation for !flag || (y + z >= x - z)

17 Short Circuit Evaluation (1) Short-circuit (minimal) evaluation - C stops evaluating a logical expression as soon as its value can be determined.  if the first part of the OR expression is true then the overall condition is true, so we don’t even look at the second part.  if the first part of the AND expression is false then the overall condition is false, so we don’t even look at the second part.  Example: if ((a d)) if (a d) is not evaluated. if ((e!=f) || (g<h)) if (e!=f) is true, (g<h) is not evaluated.  This can be significant for your program performance.

18 Short Circuit Evaluation (2) if (lname == “Smith”) && (ssn == ) if (ssn == ) && (lname == “Smith”) What is the difference? AND operator  You want to get “false” as soon as possible, since it finishes comparisons  i.e. the “most selective” test should be placed at the beginning. OR operator  You want to get “true” as soon as possible, since it finishes comparisons  i.e. the “least selective” test should be placed at the beginning and the “most selective” test at the very end.

19 Short Circuit Evaluation (3) Short circuit evaluation may cause problems for programmers who do not realize (or forget) it is happening. Example : if (condition_1 && myfunc(a)) { do_something(); }  If myfunc(a) is supposed to perform some required operation regardless of whether do_something() is executed, and condition_1 evaluates as false, then myfunc(a) will not execute, which could cause problems. Don’t perform important computations in the second half of a logical expression

20 Writing English Conditions in C Make sure your C condition is logically equivalent to the English statement.  “x and y are greater than z” (x > z) && (y > z) (valid) x && y > z (invalid)

21 Character Comparison C allows character comparison using relational and equality operators. During comparison Lexicographic (alphabetical) order is followed. (See Appendix A for a complete list of ASCII values). ‘9’ >= ‘0’ // True ‘a’ < ‘e’ // True ‘a’ <= ch && ch <= ‘z’ /* True if ch is a char type variable that contains a lower case letter.*/

22 Logical Assignment You can assign an int type variable to a non zero value for true or zero for false. Ex: even = (n%2 == 0) if (even) { do something } Some people prefer following for better readability. #define FALSE 0 #define TRUE !FALSE even = (n%2 == 0) if (even == TRUE) { do something } Some people define a separate variable type boolean.  We’ll see that in enumerated types in Ch 7.

23 Complementing a condition We can complement a logical expression by preceding it with the symbol !. We can also complement a single condition by changing its operator.  Example : The complement of ( age == 50) are !(age == 50), (age != 50)  The relational operator should change as follows, = and so on

24 DeMorgan’s Theorem (1) DeMorgan’s theorem gives us a way of simplifying logical expressions. The theorem states that the complement of a conjunction is the disjunction of the complements or vice versa. In C, the two theorems are 1.!(x || y) == !x && !y 2.!(x && y) == !x || !y Example: If it is not the case that I am tall and thin, then I am either short or fat (or both) The theorem can be extended to combinations of more than two terms in the obvious way.

25 DeMorgan’s Theorem (2) DeMorgan’s Theorems are extremely useful in simplifying expressions in which an AND/OR of variables is inverted. A C programmer may use this to re-write if (!a && !b)... as if(!(a || b)... Thus saving one operator per statement. Good, optimizing compiler should do the same automatically and allow the programmer to use whatever form seemed clear to them.

26 IF() THEN {} ELSE {} if condition {compound_statement_1 } // if condition is true else { compound_statement_2 } // if condition is false Example: if (crash_test_rating_index <= MAX_SAFE_CTRI) { printf("Car #%d: safe\n", auto_id); safe = safe + 1; } else { printf("Car #%d: unsafe\n", auto_id); unsafe = unsafe + 1; }

27 IF() THEN {} ELSE {} When the symbol { follows a condition or else, the C complier either executes or skips all statements through the matching } In the example of the previous slide, if you omit the braces enclosing the compound statements, the if statement would end after the first printf call. The safe = safe + 1; statement would always be executed. You MUST use braces if you want to execute a compound statement in an if statement. To be safe, you may want to always use braces, even if there is only a single statement.

28 No {}? if (rest_heart_rate > 56) printf("Keep up your exercise program!\n"); else printf("Your heart is in excellent health!\n"); If there is only one statement between the {} braces, you can omit the braces.

29 One Alternative? You can also write the if statement with a single alternative that executes only when the condition is true. if ( a <= b ) statement_1; Another form – seldom used, but still allowed if ( a == b ) else statement_2;

30 Nested if Statements So far we have used if statements to code decisions with one or two alternatives. A compound statement may contain more if statements. In this section we use nested if statements (one if statement inside another) to code decisions with multiple alternatives. if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else num_zero = num_zero + 1;

31 Comparison of Nested if and Sequences of ifs Beginning programmers sometime prefer to use a sequence of if statements rather than a single nested if statement if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neq + 1; if (x == 0) num_zero = num_zero +1; The book says this is less readable  I disagree with that. It is, though, less efficient because all three of the conditions are always tested. In the nested if statement, only the first condition is tested when x is positive.