Chapter 4 Selection: the if-else and switch-case instructions.

Slides:



Advertisements
Similar presentations
Chapter 4: Making Decisions.
Advertisements

Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
The If/Else Statement, Boolean Flags, and Menus Page 180
C++ Programming, Namiq Sultan1 Chapter 4 Making Decisions Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
Visual C++ Programming: Concepts and Projects
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
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 Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Computer Science Department Relational Operators And Decisions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5 Repetition or loop structure. What is repetition or loop? repeat the execution of one or a group (block; instruction enclosed in a pair of braces)
Selection Structures (if & switch statements) (CS1123)
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Basic Of Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
Fundamental Programming: Fundamental Programming Introduction to C++
CPS120: Introduction to Computer Science Decision Making in Programs.
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
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.
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
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.
Selection Structures: if and switch Statements. 2 Selection Statements –In this chapter we study statements that allow alternatives to straight sequential.
Control Structures RepetitionorIterationorLooping Part I.
1 SELECTION using IF and IF-ELSE Chapter 4. 2 Agenda Background  One Way selection (if) Two Way selection (if-else) Compound Statements Nested if-else.
Input a number #include using namespace std; int main() { int num; cout num; return 0; }
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Week 4 Program Control Structure
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,
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Chapter 3 Selection Statements
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Bill Tucker Austin Community College COSC 1315
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.
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Expression Review what is the result and type of these expressions?
Chapter 7 Conditional Statements
Flow Control Statements
Presentation transcript:

Chapter 4 Selection: the if-else and switch-case instructions

Some observations The instructions we have learned allow us to do any kind of computations (non- numeric processing will be discussed later) as long as we can convert a problem to appropriate C++ code. But we are faced with inflexibility, as illustrated in the following simple payroll problem.

Simple payroll problem to compute weekly pay for hourly workers Problem definition/specification: a worker pay is based on hours worked and hourly rate. In addition, overtime hours (those hours above 40) are paid at twice the regular rate, and any worker may work overtime. Now we have two different formulas to compute the pay for a worker, but only one will be used depending on whether the worker worker worked overtime or not. The two formulas are as follows: pay = hours * hourly_rate; // non-overtime orpay = 40.0 * hourly_rate + (hours – 40) * 2.0 * hourly_rate; // overtime

Simple payroll problem to compute weekly pay for hourly workers continued One way to get around the problem is to write two programs, one with the formula for workers who did not work overtime and the other with the formula for those who worked overtime. But that is too much work, not to mention the fact that the input data must be separately into two groups; a process that is time-consuming and potentially error prone. Can we do better? Yes, with the help of selection instructions or structures (the if-else or switch-case instructions). But first, let us define a set of operators known as relational operators.

Relational operators Relational operatorMeaningExample <less thanage < 30 >greater thanheight > 6.2 <=less than or equal totax <= >=greater than or equal totemp >= 90.0 = =equal togender = = 'M' !=not equal tox != (y + z) Using relational operator, one can write simple logical expressions (not arithmetic expressions) as shown in the "Example" column. Unlike an arithmetic expression which is evaluated to an numeric value, a logical expression is evaluated to a logical or Boolean value of either true or false. In C/C++ true is represented by 1 (or any non-zero value) and false by 0.

Example demonstrating Boolean data type #include int main( ) { bool result; result = (3 < 4); cout << "The value of 3 < 4 is" << result; result = (2.0 > 3.0); cout 3.0 is " << result << endl; return 0; }

Example demonstrating logical values #include int main( ) { cout << "The value of 3 < 4 is" << (3 < 4); cout 3.0 is " 3.0) << endl; return 0; } What will be printed?

More examples Expressionvalueinterpretation 'A' > 'C' 0false 'D' <= 'Z' 1true 'E' = = 'F' 0false 'B' != 'C' 1true

The selection structure: the if-else structure format: if ( logical expression ) { true task } else { false task } where logical expression is evaluated first; if true, the true task will be executed, otherwise, the false task will be executed. The true task or false task shown in the format is a block (of group) of any C/C++ instructions. Notice that a block of instructions is enclosed in a pair of braces (or curly brackets). If the block contains only one instruction, the braces may be skipped.

Hourly payroll problem revisited #include int main( ) { double rate, hours, total_pay; cout << "Enter hourly rate and hours worked: "; cin >> rate >> hours; if ( hours <= 40 ) total_pay = hours * rate; else total_pay = 40 * rate + (hours – 40) * 2 * rate; cout << "\nThe total pay is " << total_pay << endl; return 0; }

Program determines if an arbitrary integer is even or odd Students

Think of 11 cases where if-else (selection) are needed Each student contributes one.

Temperature conversion problem #include int main( ) { char tempType; double temp, fahren, celsius; cout << "Enter temperature to be converted: "; cin >> temp; cout <<"Enter f is the temperature is in Fahrenheit "; cout << "or c is the temperature is in Celcius: "; cin >> tempType; cout << setiosflags ( ios::fixed) << setiosflags ( ios::showpoint) << setprecision ( 2 );

Temperature conversion problem continued if ( tempType = = 'f' ) { celsius = ( 5.0 / 9.0 ) * ( temp – 32.0 ); cout << "\nThe equivalent Celsius is " << celsius << endl; } else { fahren = ( 9.0 / 5.0 ) * temp *32.0; cout << "\nThe equivalent Fahrenheit is " << fahren << endl; } return 0; } What is the user enters F or C instead of f or c?

Scope and lifetime of a variable A variable comes to life (or is born) after it is declared. From this point on, it can used or referenced from this point on for as long as the variable is within its scope. Scope of a variable –global scope: variables declared outside of a function; these variables are known as global variables. –local scope: variables declared within a function; these variables are known as local variables. block scope: defined in a block of a function function scope: declared in a function

Example on scope #include int main( ) { int a = 22, b = 33, c = 44 ; // a, b, and c have function scope cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; { // beginning of a block in a function int a = 44, b = 55; // a new set of a and b are born! // note a, b are not the same a, b declared above cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; ++ c; cout << "c now becomes " << c << endl; } // the end of the block; a and b are now 'dead' cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; return 0; }

One way selection An if statement without else branch (no false task). format: if (expression) { true task }

One way selection example: extra 5-point for perfect attendance #include int main( ) { int score; char perfectAttendance; const extraPoint = 5; cout << "Enter overall score for student: " ; cin >> score; cout << "Perfect attendance? Enter y or n: "; cin >> perfectAttendance; if ( perfectAttendance = = 'y' ) score += extraPoint; cout << "\nTotal score for the student is " << score; return 0; }

Nested if-else statement If the true-task or false-task of an if-else statement contain other if-else or if statement, the overall statement is a nested if-else statement, as illustrated in the following example.

Nested if-else example: convert a numeric to a letter grade and then print out the letter grade #include int main( ) { int score; char grade; cout << "Enter a score: " ; cin >> score; if ( score < 60 ) cout << "\nScore = " << score << " Grade = " << 'F'; else if ( score < 70 )cout << "\nScore = " << score << " Grade = " << 'D'; else if ( score < 80 )cout << "\nScore = " << score << " Grade = " << 'C'; else if ( score < 90 )cout << "\nScore = " << score << " Grade = " << 'B'; else cout << "\nScore = " << score << " Grade = " << 'A'; return 0; }

Additional example: salesperson income problem p148 … if ( sales >= ) income = * sales; else if ( sales >= ) income = * sales; else if ( sales >= ) income = * sales; else if ( sales >= ) income = * sales; else ( sales >= ) income = * sales; else income = * sales; …

switch-case selection structure Format switch (expression) { case value_1; … reak; case value_2; … break; … case value_n; … break; default: … }

switch-case example int number; … switch (number) { case 1: cout << "Good morning." << endl; break; case 2: cout << "Happy day." << endl; break; case 3: case 4: case 5: cout << "Nice evening." << endl; }