Copyright 2004-2005 - Curt Hill The C/C++ switch Statement A multi-path decision statement.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 4: Making Decisions.
True or false A variable of type char can hold the value 301. ( F )
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CIS162AD - C# Decision Statements 04_decisions.ppt.
Chapter 4 Program Control Statements
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
Flow of Control Part 1: Selection
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Module 3: Steering&Arrays #1 2000/01Scientific Computing in OOCourse code 3C59 Module 3: Algorithm steering elements If, elseif, else Switch and enumerated.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions Starting Out with C++ Early Objects Seventh Edition.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Copyright © Curt Hill The IF Revisited If part 4 Style and Testing.
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.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CS161 Introduction to Computer Science Topic #8.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
The for Statement A most versatile loop
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
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.
More important details More fun Part 3
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 4: Making Decisions.
Control Structures – Selection
Selection (if-then-else)
A Different Kind of Variable
Chapter 7 Conditional Statements
Topics 4.1 Relational Operators 4.2 The if Statement
Chapter 4: Control Structures I (Selection)
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
The Java switch Statement
Controlling Program Flow
The IF Revisited A few more things Copyright © Curt Hill.
Presentation transcript:

Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement

Copyright Curt Hill Flow of Control in C/C++ Recall the flow statements in C and C++: –Decisions If Switch Case –Loops for while do Break Here we consider the switch

Copyright Curt Hill Why? There are times when we would use the following type of nested if if(a == 2) x = 5; else if(a == 4) { x = 12 * y; … } else if(a == 8) {…} else if(a == 12) {…} else cout << “Error”;

Copyright Curt Hill General Form of This Each if has a similar condition –One variable compared with a constant –Comparison is always equality The Then statement does something The Else statement does another if There is only one variable and one comparison in all the ifs Generally such a construction needs a switch-case not an if

Copyright Curt Hill If and Switch An if is a decision of one path out of two –A bool has only two values A switch is a decision of one path out of many A switch is based on an int, char, enumeration –Which may have many values

Copyright Curt Hill General Form of Switch switch (integral expression) { case con1: many statements break; case con2: many statements break; case con3: many statements break; … }

Copyright Curt Hill Notes switch, case and break are reserved words The parenthesized expression is evaluated to obtain a value –This value chooses the path –The type of the value must be an integer, character or enumeration –May not be floating point, string or any object The case indicates a path –Must be followed by a constant –The constant value following the case must match the type of the expression –It may be a defined, literal or constant declaration

Copyright Curt Hill Example switch (credit_hours / 32) { case 0: standing = “freshman”; break; case 1: standing = “sophomore”; break; case 2: standing = “junior”; break; case 3: standing = “senior”; break; }

Copyright Curt Hill More Notes There is only one set of braces which surrounds all the cases The path starts with a case and ends with a break Multiple cases allow for multiple ways to identify a path The cases do not have to be in any particular order Duplicate cases are not allowed –Compiler actually checks for this

Copyright Curt Hill Multiple case example switch (grade) { case ‘a’: case ‘A’: points = 4 * credit_hours; break; case ‘b’: case ‘B’: points = 3 * credit_hours; break; … }

Copyright Curt Hill Missing Path What happens if the switch expression does not match any case label? Equivalent to the correct case followed by a break –It does nothing The default label allows a catch all case

Copyright Curt Hill Example Revisited AnsiString standing; switch (credit_hours / 32) { case 0: standing = “freshman”; break; … case 3: standing = “senior”; break; default: standing = “unknown”; cout << “Error”; }

Copyright Curt Hill default default is a reserved word The default label acts like a case label with out case or specifying a value It catches any value not explicitly mentioned in a case It is customarily last, but does not have to be there Leaving it out is the same as doing nothing for all the unmentioned cases

Copyright Curt Hill The Break Statement The break has the effect of leaving a switch or loop The last path does not need a break A return will also work since it leaves the entire function/method not just the switch It is not required, but leaving it out makes for interesting flow

Copyright Curt Hill Leaving out a break If a break is left out, execution will drop into the next part Leaving out the last break is not a problem since there is no next part Consider the following example

Copyright Curt Hill Omitted break example switch (val) { case 5: x += 5; case 12: x += 8; y = 2; break; case 6: x += 8; y = 4; break; } If val is 5, x will have 13 added to it and y will be set to 2. All the effect of val == 12 is also executed for x == 5.

Copyright Curt Hill Omitted break notes This feature, inherited from C, is both good and bad It is somewhat good in that it allows an economy of code –Very few switches actually use this feature It is usually bad because we seldom want it but the compiler never gives an error when a break is left out

Copyright Curt Hill Equivalence of if and switch We have already seen an if doing what a switch can do The reverse is also true: switch(b>c){ case true: …. break; case false: …. break; } Always use what is more natural

Copyright Curt Hill Common mistakes We cannot use strings or other objects for the case expression or labels We cannot use floating point values (float or double) for the expression or case labels –Recall the problems with floating point equality

Copyright Curt Hill Uses switch is much less used than an if –Just not as much need for it Often used to decode an integer or enumeration into a string –Month number into a name Used to select different actions for these as well Often used for a menu in console programs

Copyright Curt Hill Readability Indenting things is again the rule My choice: –Indent the case –Indent the code past the case Example: switch (item) { case 1: duh = duh2; … break case 2: … }

Enumerations and Switch We frequently use switch to input, output and decode enumerations Lets look at enumeration examples Suppose: enum colortype {ctRed, ctGreen, ctBlue, ctWhite, ctBlack} color; Copyright Curt Hill

Display For displayable output use a switch: String s = “None”; switch (color) { case ctRed: s = “Red”; break; case ctGreen: s = “Green”; break; … } // end of switch Copyright Curt Hill

Copyright © Curt Hill Input Several approaches Read in integer and use switch case to make into enumeration Read in string and use nested ifs to create enumeration

Input with integer In a console program: cout > val; switch (val){ case 0: color = ctRed; break; case 1: … The same may be done using text input from windows Copyright Curt Hill

Decoding Decoding is using an enumeration to perform different actions Consider: switch (action){ case aExit: Close(); break; case aAbout: Application->MessageBox(… … Copyright Curt Hill

Finally Switch is the one of many decision Switch is the least used decision –Many more ifs than switches –Less frequently used than most loops Use it when the pattern is seen if (a==1) … else if (a==3) … else if (a==2) … Copyright © Curt Hill