ICS103: Programming in C 4: Selection Structures

Slides:



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

Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
true (any other value but zero) false (zero) expression Statement 2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
1 ICS103 Programming in C Lecture 6: Selection Structures.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
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
Chapter 4 Selection Structures: Making Decisions.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Decision Statements, Short- Circuit Evaluation, Errors.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
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.
CNG 140 C Programming (Lecture set 3)
Chapter 3 Control Statements
Selections Java.
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.
Decisions Chapter 4.
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Java Programming: Guided Learning with Early Objects
Control Structures – Selection
Selection Structures: if and switch Statements
Decision I (if Statement)
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Chapter 4: Selection Structures: if and switch Statements
CprE 185: Intro to Problem Solving (using C)
Chap 7. Advanced Control Statements in Java
Flow of Control.
3.0 - Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal.
Presentation transcript:

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

Outline Control Structures Conditions, Relational, and Logic Operators The if Statement and Flowchart if with Compound Statements Nested if statements The switch Statement Operator Precedence, Complementing a Condition Common Programming Errors

Control Structures Control structure Three kinds of control structures Control the flow of execution in a program or a function Three kinds of control structures Sequence (Compound Statement) Selection (if and switch Statements) Repetition [Chapter 5] Selection control structure Chooses among alternative program statements

Compound Statement A group of statements bracketed by { and } Executed Sequentially A function body consists of a compound statement { statement1 ; statement2 ; . . . statementn ; } Compound Statement Specifies Sequential Execution

Conditions Condition Conditions are used in if statements, such as: An expression that evaluates to false (0) or true (1) Conditions are used in if statements, such as: if (a >= b) printf("a is greater or equal to b"); else printf("a is less than b"); The condition in the above example: (a >= b)

Relational and Equality Operators Meaning Type < less than relational > greater than <= less than or equal to >= greater than or equal to == equal to equality != not equal to Evaluate to either false (0) or true (1)

Examples of Relational and Equality Operators -5 x 1024 i MAX 7 y 5.5 item 7.2 mean 'M' ch 999 num Operator Condition Value <= x <= 0 true (1) < i < MAX false (0) >= x >= y > item > mean == ch == 'M' != num != MAX

Logical Operators Three Logical Operators && logical AND || logical OR ! logical NOT Truth Table for logical operators A B (A && B) (A || B) !A true false

Logical Expressions Logical Expression Logical Expression Value Condition that uses one or more logical operators 1050 salary 38.2 temperature 0.85 humidity 101 n 6 children Logical Expression Value salary < 1000 || children > 4 true (1) temperature > 35.0 && humidity > 0.90 false (0) n >= 0 && n <= 100 !(n >= 0 && n <= 100)

Comparing Characters We can also compare characters in C Expression Using the relational and equality operators Expression Value '9' >= '0' 1 (true) 'a' < 'e' 'B' <= 'A' 0 (false) 'Z' == 'z' 'A' <= 'a' ch >= 'a' && ch <= 'z' ch is lowercase?

English Conditions as C Expressions Logical Expression x and y are greater than z x > z && y > z x is equal to 1 or 3 x == 1 || x == 3 x is in the range min to max x >= min && x <= max x is outside the range z to y x < z || x > y

Next . . . Control Structures Conditions, Relational, and Logic Operators The if Statement and Flowchart if with Compound Statements Nested if statements The switch Statement Operator Precedence, Complementing a Condition Common Programming Errors

if Statement (One Alternative) if (condition) statementT ; if condition evaluates to true then statementT is executed; Otherwise, statementT is skipped Example: if (x != 0.0) product = product * x ;

if Statement (Two Alternatives) if (condition) statementT ; else statementF ; if condition evaluates to true then statementT is executed and statementF is skipped; Otherwise, statementT is skipped and statementF is executed Example: if (x >= 0.0) printf("Positive"); else printf("Negative");

Flowcharts of if Statements Two Alternatives if-else statement One Alternative if statement

if with Compound Statements if (ch >= 'A' && ch <= 'Z') { printf("Letter '%c' is Uppercase\n", ch); ch = ch – 'A' + 'a'; printf("Converted to lowercase '%c'\n", ch); } else { printf("'%c' is not Uppercase letter\n", ch); printf("No conversion is done\n");

Hand Tracing an if Statement if (x > y) { /* switch x and y */ temp = x; /* save x in temp */ x = y; /* x becomes y */ y = temp; /* y becomes old x */ } if statement x y temp Effect 12.5 5.0 ? if (x>y) { 12.5>5.0 is true temp = x ; Store old x in temp x = y ; Store y in x y = temp ; Store old x in y

Next . . . Control Structures Conditions, Relational, and Logic Operators The if Statement and Flowchart if with Compound Statements Nested if statements The switch Statement Operator Precedence, Complementing a Condition Common Programming Errors

Nested if Statements Nested if statement Example if statement inside another if statement Program decisions with multiple alternatives Example if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else /* x equals 0 */ num_zero = num_zero + 1;

Multiple-Alternative Decision Form The conditions are evaluated in sequence until a true condition is reached If a condition is true, the statement following it is executed, and the rest is skipped if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else /* x equals 0 */ num_zero = num_zero + 1; More Readable

Sequence of if Statements All conditions are always tested (none is skipped) Less efficient than nested if for alternative decisions if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neg + 1; if (x == 0) num_zero = num_zero + 1; Less Efficient than nested if

Implementing a Decision Table Use a multiple-alternative if statement to implement a decision table that describes several alternatives Salary Range ($) Base Tax Rate Salary < $15,000 $0 15% $15,000 ≤ Salary < $30,000 $2,250 18% $30,000 ≤ Salary < $50,000 $4,950 22% $50,000 ≤ Salary < $80,000 $9,350 27% Salary  $80,000 $17,450 33%

Computing the Tax from a Table if (salary < 15000) tax = 0.15*salary; else if (salary < 30000) tax = 2250 + (salary – 15000)*0.18; else if (salary < 50000) tax = 4950 + (salary – 30000)*0.22; else if (salary < 80000) tax = 9350 + (salary – 50000)*0.27; else tax = 17450 + (salary – 80000)*0.33;

Road Sign Decision You are writing a program to control the warning signs at the exists of major tunnels. 'S' means road is Slick or Slippery temperature

Road Sign Nested if Statement if (road_status == 'S') if (temp > 0) { printf("Wet roads ahead\n"); printf("Stopping time = 10 minutes\n"); } else { printf("Icy roads ahead\n"); printf("Stopping time = 20 minutes\n"); else printf("Drive carefully!\n"); C associates else with the most recent incomplete if

Next . . . Control Structures Conditions, Relational, and Logic Operators The if Statement and Flowchart if with Compound Statements Nested if statements The switch Statement Operator Precedence, Complementing a Condition Common Programming Errors

The switch Statement User Input Operation Can be used to select one of several alternatives Based on the value of a variable or simple expression Variable or expression may be of type int or char But not of type double Example: Simple Calculator User Input Operation '+' result = a + b; '–' result = a – b; '*' result = a * b; '/' result = a / b;

Example of a switch Statement switch (op) { // op must be of type char case '+': result = a + b; break; case '-': result = a – b; case '*': result = a * b; case '/': result = a / b; default: printf("Error: unknown operation %c\n", op); return; // to terminate the function } Example of a switch Statement

Explanation of switch Statement It takes the value of the character op and compares it to each of the cases in a top down approach. It stops after it finds the first case that is equal to the value of the variable op. It then starts to execute each line following the matching case till it finds a break statement. If no case is equal to the value of op, then the default case is executed. default is optional. If no other case is equal to the value of the controlling expression and there is no default case, the entire switch body is skipped.

More About the switch Statement One or more C statements may follow a case label. You do not need to enclose multiple statements in curly brackets after a case label. You cannot use a string as a case label. case "Add": is not allowed Do not forget break at the end of each alternative. If the break statement is omitted then execution falls through into the next alternative. Do not forget the { } of the switch statement.

Nested if Versus switch Nested if statements More general than a switch statement Can implement any multiple-alternative decision Can be used to check ranges of values Can be used to compare double values switch statement Syntax is more readable Implemented more efficiently in machine language Use switch whenever there are few case labels Use default for values outside the set of case labels

Next . . . Control Structures Conditions, Relational, and Logic Operators The if Statement and Flowchart if with Compound Statements Nested if statements The switch Statement Operator Precedence, Complementing a Condition Common Programming Errors

Operator Precedence Operator Precedence function calls highest ! + - & (unary operators) * / % + – < <= >= > == != && (logical AND) || (logical OR) = (assignment operator) lowest

Evaluation Tree, Step-by-Step Evaluation )

Short-Circuit Evaluation Stopping the evaluation of a logical expression as soon as its value can be determined Logical-OR expression of the form (a || b) If a is true then (a || b) must be true, regardless of b No need to evaluate b However, if a is false then we should evaluate b Logical-AND expression of the form (a && b) If a is false then (a && b) must be false, regardless of b However, if a is true then we should evaluate b Can be used to prevent division by zero (divisor != 0 && x / divisor > 5)

Logical Assignment Use assignment to set int variables to false or true The false value is zero C accepts any non-zero value as true Examples of Logical Assignment senior_citizen = (age >= 65); even = (n%2 == 0); uppercase = (ch >= 'A' && ch <= 'Z'); lowercase = (ch >= 'a' && ch <= 'z'); is_letter = (uppercase || lowercase);

Complementing a Condition DeMorgan's Theorem !(expr1 && expr2) == (!expr1 || !expr2) !(expr1 || expr2) == (!expr1 && !expr2) Example Equivalent Expression !(item == 5) item != 5 !(age >= 65) age < 65 !(n > 0 && n < 10) n <= 0 || n >= 10 !(x == 1 || x == 3) x != 1 && x != 3 !(x>y && (c=='Y' || c=='y')) (x<=y) || (c!='Y' && c!='y')

Common Programming Errors Do Not write: if (0 <= x <= 4) 0 <= x is either false (0) or true (1) Then, false(0) or true(1) are always <= 4 Therefore, (0 <= x <= 4) is always true Instead, write: if (0 <= x && x <= 4) Do Not write: if (x = 10) = is the assignment operator x becomes 10 which is non-zero (true) if (x = 10) is always true Instead, write: if (x == 10)

More Common Errors In if statements: Don’t forget to parenthesize the if (condition) Don’t forget { and } in if with compound statements Correct pairings of if and else statements: C matches else with the closest unmatched if In switch statements: Make sure the controlling expression and case labels are of the same permitted type (int or char) Remember to include the default case Don’t forget { and } for the switch statement Don’t forget the break at the end of each case