Switch Statements. Switch Statement Often you want to do a series of tests –if i==0 … else if i==1 …. else if i==2 … else if i==3 …. C++ provides the.

Slides:



Advertisements
Similar presentations
If Statements & Relational Operators Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Conditional Operator (?:) Conditional operator (?:) takes three arguments (ternary) Syntax for using the conditional operator:
Switch Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
CS Sept 2006 Pick ups from chapters 4 and 5.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
CS 1400 Pick ups from chapters 4 and 5. if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
Chapter 4 Making Decisions
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Programming in C++ Lecture Notes 2 – Choice Statements Andreas Savva.
Chapter 4 Program Control Statements
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
Selection Statements in C++ If Statement in C++ Semantics: These statements have the same meaning as in the algorithmic language. 2- Two way selection:
Computer Science Department Relational Operators And Decisions.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Selection Structures (if & switch statements) (CS1123)
Basic Of Computer Science
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Selection Control Structures (L08) * Selection Criteria * if Statements * The if-else Statement Selection Control Structure Dr. Ming Zhang.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
1 CS161 Introduction to Computer Science Topic #8.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
LESSON 4 Decision Control Structure. Decision Control Structures 1. if statement 2. if-else statement 3. If-else-if statement 4. nested if statement 5.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Switch Statements Comparing Exact Values
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
משפטי תנאי ( לוגיקה ) קרן כליף. 2 © Keren Kalif ביחידה זו נלמד :  משפטי תנאי  משפט switch  משפט if מקוצר.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Branching statements.
Chapter 3 Selection Statements
Chapter 3 Control 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.
LESSON 4 Decision Control Structure
לולאות קרן כליף.
Compound Assignment Operators in C++
Flow Control Statements
Selection Control Structure
Chapter 4: Control Structures I (Selection)
Structured Program Development in C++
do/while Selection Structure
Branching statements Kingdom of Saudi Arabia
The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)
HNDIT11034 More Operators.
Selection Control Structure
C++ Programming Lecture 7 Control Structure I (Selection) – Part II
Presentation transcript:

Switch Statements

Switch Statement Often you want to do a series of tests –if i==0 … else if i==1 …. else if i==2 … else if i==3 …. C++ provides the switch statement to help in this situation –It allows you to specify a large set of cases you want to be able to match, yet works efficiently to find and execute the particular case matched

Format Format: switch (switchExpression ) { case value1: statements; break; case value2: statements; break; … default: statements; } Example: ………… int mortgageTerm; float interestRate; cin>> mortgageTerm; Switch (mortgageTerm) { case 10: interestRate= 3.0; break; case 15: interestRate=3.5; break; case 30: interestRate=4.0; break; default: cout<<“please enter a valid loan term”; }

char grade; cin >> grade; switch (grade) { case 'A': cout << "Great job!!"; break; case 'B': cout << "Good job"; break; case 'C': cout << "Satisfactory job"; break; case 'D': cout << "Hmmm... need to work a little harder"; break; case 'F': cout << "Sorry, you failed the class"; break; default: cout << "The letter you typed " << grade << " is not a valid grade"; } Examples

Examples: #include using namespace std; int main() { int operand1 = 0, operand2 = 0, result=0; char operator = ‘ ‘; cout << “Please enter expression (num oper num) ? “; cin >> operand1 >> operator >> operand2; switch (operator) { case ‘+’: result = operand1 + operand2; break; case ‘-’: result = operand1 - operand2; break; // other cases left off for room default: cout << “Did not recognize operator” << endl; } cout << operand1 << “ “ << operator << “ “ <<operand2 << “ = “ << result << endl; return 0; }

Examples int x, y; cin>>x>>y; switch (x>y) { case 0: cout<<“x is no greater than y”; break; case 1: cout<<“ x is greater than y”; break; default: } int x, y; cin>>x>>y; switch (x>y) { case false: cout<<“x is no greater than y”; break; case true: cout<<“ x is greater than y”; break; default: }

Fall Through Example: …. switch (flight_class) { case 3: ticket=300; case 2: ticket=500; case 1: ticket=1000; } cout<<“you need to pay”<<“\” ticket <<“dollars, thank you!”<<endl; What the third class passenger will need to pay? Switch (flight_class) { Case 3: ticket=300; break; Case 2: ticket=500; break; Case 1:ticket=1000; break; Default: cout<<“unknown class!”; }

Exercise Convert the following segment of code to switch statement: int j, n; ….. If (j==3 || j==5) n = 6; else if ( j==4 || j==8) n = 9; else if (j==2) n = 8; else n=0;

Exercise: What the output will be? #include using namespace std; int x=1, y=2, z=3; int main(){ switch (x>0) { case 1: switch (y<0) { case 1: cout<<“?”; break; case 2: cout<<“%”; break; } case 0: switch (z==3) { case 0: cout<<“+”; break; case 1: cout<<“#”; break; } default: cout<<“&”; } return 0; }

Switch Statement Style ideas for the switch statement –Unless you have many conditions (4 or more), use if-else-if instead of switch –Always provide a default case – if you are pretty sure you have all cases covered, putting an error message in the default is good to identify unexpected errors –Order the cases in some logical order (numeric, alphabetic) –Keep the size of each of the cases small If you have to do lots of work in each case, call a function from inside the case