CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.

Slides:



Advertisements
Similar presentations
Selection Structures: if and switch Statements
Advertisements

ICS103: Programming in C 4: Selection Structures Muhamed F. Mudawar.
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Chapter 4 Selection Structures: if and switch Statements Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering.
1 ICS103 Programming in C Ch4: Selection Structures.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Lab 6 rOperators l Relational Operators l Equality Operators l Logical Operators rIf statement l One Alternative l With Compound Statement l Nested If.
1 TDBA66, VT-03, Lecture - Ch. 4 Control structures Conditions (expr1 op expr2 op expr3..) Choise (if statements) Repetition (loops) see Chap. 5.
CS 201 Selection Structures (2) and Repetition
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.
C++ for Engineers and Scientists Third Edition
1 ICS103 Programming in C Lecture 6: Selection Structures.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Conditional Statement
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4 Selection Structures: if and switch Statements Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
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)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Flow of Control Part 1: Selection
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
Department of CSE Control Structures: Selection.
Week 4 Program Control Structure
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
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.
Decision making If.. else statement.
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: Making Decisions.
Selection Structures: if and switch Statements
Decision making If statement.
Week 3 – Program Control Structure
Chapter 4: Selection Structures: if and switch Statements
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements

Outline Control Structures Control Structures Conditions Conditions The if Statement The if Statement Decision Steps in Algorithms: Case Study Decision Steps in Algorithms: Case Study The switch Statement The switch Statement Common Programming Errors Common Programming Errors

Control Structures All programs can be written with three basic structures All programs can be written with three basic structures  Sequence  Selection  Repetition (Looping, Iteration) Compound statement Compound statement{ Statement 1; …… Statement n; }

Selection Process 1Process 2 Condition

Condition An expression to perform comparisons, which is either false (represented by 0) or true (usually represented by 1, actually could be anything other than 0) An expression to perform comparisons, which is either false (represented by 0) or true (usually represented by 1, actually could be anything other than 0) Relational expressions Relational expressions Logical expressions Logical expressions

Relational Expressions operand relational operator operand operand relational operator operand OperatorMeaningExample < less than age < 30 > greater than age > 30 <= less than or equal to taxable <= 20 >= greater than or equal to temp >= 98.6 == equal to grade == 90 != not equal to number != 250

Character Examples ‘1’ < ‘7’ 1True ‘D’ <= ‘Z’ 1True ‘c’ >= ‘v’ 0False ‘m’ <= ‘M’ System dependent ‘b’ == ‘B’ 0False

More Examples key = ‘ m ’ ; i = 5; j = 7; k = 12; x = 22.5; (i + 2) = = (k – 1) ((3 * i) – j) < 22 (i + (2 * j)) > k (‘a’ + 1) = = ‘b’ (k + 3) <= ((-j) + (3 * i)) (key – 1) > ‘p’ (key + 1) == ‘n’ 25 <= (x + 1.0)

Logical Expressions operand logical operator operand OperatorNameUseTruth && Logical and (a > 10) && (b < 20) (b < 20) both operands true || Logical or (a > 10) || (b < 20) either operand true ! Logical complement !(a == b) complement operand

OperatorPrecedence function calls ! + - & (unary operators) * / % + - = > = > == != &&||= Operator Precedence highest lowest

Examples x = 3.0; y = 4.0; z = 2.0; flag = 0; 1. !flag 2. x + y / z <= !flag || (y + z >= x – z) 4. !(flag || (y + z >= x – z)) Short-circuit evaluation Short-circuit evaluation

English Condition in C English Condition Logical Expression x and y are greater than z x is equal to 1.0 or 3.0 x is in the range z to y, inclusive x is outside the range z to y

Complementing a Condition Complementing item == SENT: Complementing item == SENT: ! (item == SENT) or item != SENT DeMorgan ’ s Theorem DeMorgan ’ s Theorem  The complement of expr 1 && expr 2 is written as comp 1 || comp 2, where comp 1 is the complement of expr 1 and comp 2 is complement of expr 2  The complement of expr 1 || expr 2 is written as comp 1 && comp 2, where comp 1 is the complement of expr 1 and comp 2 is complement of expr 2  age <= 25 && (status == ‘S’ || status == ‘D’)

Logical Assignment int senior_citizen; senior_citizen = (age >= 65); Expression !senior_citizen && gender == ‘ M ’ int in_range, is_letter; in_range = (n > -10 && n -10 && n < 10); is_letter = (ch >= ‘ A ’ && ch = ‘ A ’ && ch <= ‘ Z ’ ) || (ch >= ‘ a ’ && ch = ‘ a ’ && ch <= ‘ z ’ ); int even; even = (n % 2 == 0);

The if Statement Syntax Syntax if (condition) statement1;elsestatement2; If condition is true, statement1 will be executed If condition is true, statement1 will be executed If condition is false, statement2 will be executed If condition is false, statement2 will be executed The else part is optional The else part is optional

Examples if (crsr_or_frgt == ‘ C ’ ) printf( “ Cruiser\n ” ); else printf( “ Frigate\n ” ); if crsr_or_frgt == ‘ C ’ printf( “ Cruiser\n ” ); if (crsr_or_frgt == ‘ C ’ ); printf( “ Cruiser\n ” ); Display “Cruiser” Display “Frigate” == ‘C’ ? TF

Compound Statements Syntax Syntax if (condition) { statements; }else } if (ctri <= MAX_SAFE_CTRI) { printf( “ Car #%d: safe\n ”, auto_id); safe = safe + 1; } else { printf( “ Car #%d: unsafe\n ”, auto_id); unsafe = unsafe + 1; } if (ctri <= MAX_SAFE_CTRI) printf( “ Car #%d: safe\n ”, auto_id); safe = safe + 1; else ……

Example if (x > y) { temp = x; /* Store old x in temp */ x = y; /* Store old y in x */ y = temp; /* Store old x in y */ } Tracing its execution with x = 12.5; y = 5.0;

Tracing an if Statement Statementsxytemp ? if (x > y) { temp = x; temp = x; x = y; x = y; y = temp; y = temp;

Nested if Statements if (expression1) statement1;else if (expression2) statement2;elsestatement3;

if (x > 0) num_pos = num_pos + 1; else if (x < 0) num_neg = num_neg + 1; else num_zero = num_zero + 1; if (x > 0) num_pos = num_pos + 1; if (x < 0) num_neg = num_neg + 1; if (x == 0) num_zero = num_zero + 1;

Multiple Variables to Test /* print a message if all criteria are met */ if (marital_status == ‘S’) if (gender == ‘M’ ) if (gender == ‘M’ ) if (age >= 18) if (age >= 18) if (age <= 26) if (age <= 26) printf(“ All criteria are met. \n”); printf(“ All criteria are met. \n”); if (marital_status == ‘S’ && gender == ‘M’ && age >= 18 && age = 18 && age <= 26 ) printf(“ All criteria are met. \n”); printf(“ All criteria are met. \n”);

if (road_status == ‘ S ’ ) if (temp > 0) { printf( “ Wet roads ahead\n ” ); printf( “ Stopping time doubled\n ” ); } else { printf( “ Icy roads ahead\n ” ); printf( “ Stopping time quadrupled\n ” ); }else printf( “ Drive carefully\n ” );

Nested if Statements May be nested to any depth May be nested to any depth Each “ statement ” may be a compound statement else matches closest unmatched if Braces may be used to change if-else matching

Example What is the difference, if any? if (expression1) if (expression2) statement1; else statement2; if (expression1) if (expression2) statement1; else statement2;

if (road_status == ‘ D ’ ) printf( “ Drive carefully\n ” ); else if (temp > 0) { printf( “ Wet roads ahead\n ” ); printf( “ Stopping time doubled\n ” ); } else { printf( “ Icy roads ahead\n ” ); printf( “ Stopping time quadrupled\n ” ); }

Multiple-Alternative Decision if (expression_1) statement_1; else if (expression_2) statement_2;…… else if (expression_n) statement_n;elsestatement_e;

Example if (marks >= 75) printf ( “ Distinction\n ” ) ; printf ( “ Distinction\n ” ) ; else if (marks >= 60) printf ( “ Pass\n ” ) ; printf ( “ Pass\n ” ) ; else if (marks >= 50) printf ( “ Average\n ” ) ; printf ( “ Average\n ” ) ;else printf ( “ Fail\n ” ) ; printf ( “ Fail\n ” ) ; if (marks >= 50) printf ( “ Average\n ” ) ; printf ( “ Average\n ” ) ; else if (marks >= 60) printf ( “ Pass\n ” ) ; printf ( “ Pass\n ” ) ; else if (marks >= 75) printf ( “ Distinction\n ” ) ; printf ( “ Distinction\n ” ) ;else printf ( “ Fail\n ” ) ; printf ( “ Fail\n ” ) ; Order of the conditions will affect the outcome as well as efficiency.

Decision Table Salary Range ($) Base Tax ($) Percentage of Excess , , , , , , , , , , , , ,

Case Study: Computing Compass Bearings Problem: Write a program that automates the table you use to transform compass headings in degrees (0 to 360 degrees) to compass bearings. The program should require entry of a compass heading, such as 110 degrees, and should display the corresponding bearing (e.g. south 70 degrees east). Problem: Write a program that automates the table you use to transform compass headings in degrees (0 to 360 degrees) to compass bearings. The program should require entry of a compass heading, such as 110 degrees, and should display the corresponding bearing (e.g. south 70 degrees east).

Analysis Analysis  Input: double heading; /* in degree */  Output: equivalent bearing message (direction you face, an angle between 0-90, direction to turn) Heading in Degrees Bearing Computation 0 – …… north (heading) east 90 – …… south (180.0 – heading) east 180 – …… south (heading – 180.0) west 270 – 360 north (360.0 – heading) west

Case Study Design Design  Initial Algorithm: 1. Display instructions 1. Display instructions 2. Get the compass heading 2. Get the compass heading 3. Display the equivalent compass bearing 3. Display the equivalent compass bearing  Algorithm Refinement on Step 3 multiple alternative if statements multiple alternative if statements catch the value out of range (0, 360), show the error message catch the value out of range (0, 360), show the error message

The switch Statement switch ( integer or char expression ) { caseconst1: statements 1 break; caseconst2: statements 2; break; …… default: statements d; break; }

switch Selection is based on one variable or expression Selection is based on one variable or expression MUST have INTEGER or CHAR condition for branching MUST have INTEGER or CHAR condition for branching Like a special instance of if else-if else... Like a special instance of if else-if else... Evaluates expression then compares it to CONSTANT VALUES in each case Evaluates expression then compares it to CONSTANT VALUES in each case

switch There can be as many “case” values as needed There can be as many “case” values as needed There can be as many “ statements ” as needed following the ‘ : ’ (no brace needed) There can be as few “statements” as needed following the ‘:’ There can be as few “statements” as needed following the ‘:’ The default statement is optional

Flowchart of switch Statement ? 123default

switch (class) { case 'B': case 'b': printf("Battleship\n"); break; case 'C': case 'c': printf("Cruiser\n"); break; case 'F': case 'f': printf("Frigate\n"); break; default: printf("Unknown ship class %c\n", class); }

/* determine average life expectancy of a standard light bulb */ switch (watts) { case 25: life = 2500; break; case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; }

Common Programming Errors Cannot use a a && x a && x < b e.g. if (0 <= x <= 4) printf(“Condition is true\n”); When x = 5, what is the result? When x = 5, what is the result? Equality operator is == instead of = Equality operator is == instead of = e.g. int age = 30; if (age = 40) if (age = 40) printf(“Happy Birthday”); Always prints Happy Birthday!!!!

Common Programming Errors if (condition) { if (condition) { …… …… } Use braces to change the if-else order Use braces to change the if-else order Always try to use multiple alternative format when writing a nested if statement Always try to use multiple alternative format when writing a nested if statement else match with closest unmatched if else match with closest unmatched if switch statement format switch statement format