Straight-line code (or IPO: Input-Process-Output) If/else & switch. Relational Expressions. Decisions. Sections 4.1-6, , 4.

Similar documents
Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Hardware Components Illustrated

3.1 The cin Object. Expressions & I/O. Console Input. Example program using cin. Unit 2. Sections 2.14, , 5.1, CS 1428 Spring 2018

l A program is a set of instructions that the l It must be translated l Variable: portion of memory that stores a value char

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-3,5

Arrays. Array Data Type. Array - Memory Layout. Array Terminology. Gaddis: 7.1-4,6

Searching, Sorting & Analysis

Structures. Data Types Structures. Data Types (C/C++) Gaddis: A Data Type consists of: Unit 7. example: Integer. CS 1428 Spring 2018

Week 4. Pointers and Addresses. Dereferencing and initializing. Pointers as Function Parameters. Pointers & Structs. Gaddis: Chapters 9, 11

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Outerjoins, Constraints, Triggers

file://j:\macmillancomputerpublishing\chapters\in073.html 3/22/01

Infinity Connect Web App Customization Guide

5. Selection: If and Switch Controls

LECTURE 04 MAKING DECISIONS

l Tree: set of nodes and directed edges l Parent: source node of directed edge l Child: terminal node of directed edge

Special Edition Using Microsoft Excel Selecting and Naming Cells and Ranges

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

l A set is a collection of objects of the same l {6,9,11,-5} and {11,9,6,-5} are equivalent. l There is no first element, and no successor of 9.

Searching & Sorting. Definitions of Search and Sort. Other forms of Linear Search. Linear Search. Week 11. Gaddis: 8, 19.6,19.8.

IBC DOCUMENT PROG007. SA/STA SERIES User's Guide V7.0

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Chapter 4 - Notes Control Structures I (Selection)

Language Identification for Texts Written in Transliteration

An Optimizing Compiler

End To End Software Developer Training

Control Statements. If Statement if statement tests a particular condition

Searching & Sorting. Definitions of Search and Sort. Other forms of Linear Search. Linear Search. Week 11. Gaddis: 8, 19.6,19.8. CS 5301 Spring 2017

MCSE Training Guide: Windows Architecture and Memory

A Petrel Plugin for Surface Modeling

Register Allocation. Consider the following assignment statement: x = (a*b)+((c*d)+(e*f)); In posfix notation: ab*cd*ef*++x

Flow Control. CSC215 Lecture

Tutorial 3 Concepts for A1

Insert the power cord into the AC input socket of your projector, as shown in Figure 1. Connect the other end of the power cord to an AC outlet.

PL/SQL, Embedded SQL. Lecture #14 Autumn, Fall, 2001, LRX

Decisions. Arizona State University 1

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

l A set is a collection of objects of the same l {6,9,11,-5} and {11,9,6,-5} are equivalent. l There is no first element, and no successor of 9.

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Topics. Chapter 5. Equality Operators

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Software Design & Programming I

3GPP TS V7.1.0 ( )

More Relation Model: Functional Dependencies

NCH Software Spin 3D Mesh Converter

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

A METHOD FOR GRIDLESS ROUTING OF PRINTED CIRCUIT BOARDS. A. C. Finch, K. J. Mackenzie, G. J. Balsdon, G. Symonds

Nearest Neighbor Learning

5. Control Statements

Revisions for VISRAD

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18

Lecture 3 Tao Wang 1

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Solutions to the Final Exam

Other Loop Options EXAMPLE

Extracting semistructured data from the Web: An XQuery Based Approach

Chapter 3: Introduction to the Flash Workspace

C++ Programming: From Problem Analysis to Program Design, Third Edition

MCSE TestPrep SQL Server 6.5 Design & Implementation - 3- Data Definition

Data Management Updates

If your PC is connected to the Internet, you should download a current membership data file from the SKCC Web Server.

Looping. Arizona State University 1

Meeting Exchange 4.1 Service Pack 2 Release Notes for the S6200/S6800 Servers

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)

Add Subtract Multiply Divide

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

FOR SERVICE TECHNICIAN S USE ONLY

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Professor: Alvin Chao

SQL3 Objects. Lecture #20 Autumn, Fall, 2001, LRX

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

As Michi Henning and Steve Vinoski showed 1, calling a remote

The Big Picture WELCOME TO ESIGNAL

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

understood as processors that match AST patterns of the source language and translate them into patterns in the target language.

Avaya Extension to Cellular User Guide Avaya Aura TM Communication Manager Release 5.2.1

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Supporting Top-k Join Queries in Relational Databases

2 nd Week Lecture Notes

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

UEE1302(1102) F10: Introduction to Computers and Programming

Lecture outline Graphics and Interaction Scan Converting Polygons and Lines. Inside or outside a polygon? Scan conversion.

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

Databases and PHP. Accessing databases from PHP

BEA WebLogic Server. Release Notes for WebLogic Tuxedo Connector 1.0

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Layout Conscious Approach and Bus Architecture Synthesis for Hardware-Software Co-Design of Systems on Chip Optimized for Speed

Sect 8.1 Lines and Angles

C48C SERIES - 1/16 DIN COUNTERS

CHAPTER : 9 FLOW OF CONTROL

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

RDF Objects 1. Alex Barnell Information Infrastructure Laboratory HP Laboratories Bristol HPL November 27 th, 2002*

Transcription:

If/ese & switch Unit 3 Sections 4.1-6, 4.8-12, 4.14-15 CS 1428 Spring 2018 Ji Seaman Straight-ine code (or IPO: Input-Process-Output) So far a of our programs have foowed this basic format: Input some vaues Do some computations Output the resuts The statements are executed in a sequence, first to ast. 1 2 Decisions Sometimes we want to be abe to decide which of two statements to execute: N fee is 2.9% monthy saes > $3,000 Y fee is 2.5% Reationa Expressions Making decisions require being abe to ask Yes or No questions. Reationa expressions aow us to do this. Reationa expressions evauate to true or fase. Aso caed: ogica expressions conditiona expressions booean expressions 3 4

Reationa Expressions 4.1 Reationa Operators Booean iteras: Binary operators used to compare expressions: true fase true evauates to true Booean variabes fase evauates to fase < Less than <= Less than or equa to > Greater than >= Greater than or equa to == Equas (note: do not use =)!! boo ispositive = true; boo found = fase;!= Not Equas ispositive evauates to true found evauates to fase 5 6 Reationa Expressions Reationa Operator Precedence Exampes: int x=6; int y=10; a. x == 5 evauates to fase b. 7 <= x + 2 evauates to c. y 3 > x evauates to d. x!= y evauates to d. true evauates to true Reationa operators are LOWER than arithmetic operators: int x, y; x < y -10 // minus happens first x * 5 >= y + 10 // mut, then pus, then >= Can assign reationa expressions to variabes: boo ispositive; int x; cin >> x; ispositive = x > 0; if the user types: 25 ispositive stores the vaue Reationa operators are HIGHER than assignment: int x, y; boo t1 = x > 7; // > then = boo t2 = x * 5 >= y + 10; // *, +, >=, = 7 8

4.2 The if statement The if statement can be used to execute a statement ony under certain conditions: if (expression) statement expression is evauated If it is true, then statement is executed. If it is fase, then statement is skipped if statement exampe Exampe: An empoyee gets a $100 bonus if their hours are over 40. doube rate = 14.50; doube hours, pay; cout << Enter the hours you worked: ; cin >> hours; pay = hours * rate; if (hours > 40) pay = pay + 100; cout << Your pay is: $ << pay << end; 9 10 4.3 The bock statement if with a bock a bock (or a compound statement) is a set of statements inside braces: { int x; cout << Enter a vaue for x: << end; cin >> x; cout << Thank you. << end; We can use a bock to conditionay execute more than just one statement: doube rate = 14.50; doube hours, pay; cout << Enter the hours you worked: ; cin >> hours; This groups severa statements into a singe statement. This aows us to use mutipe statements when by rue ony one is aowed. pay = hours * rate; if (hours > 40) { pay = pay + 100; cout << Your pay incudes a bonus. << end; cout << Your pay is: $ << pay << end; 11 12

4.4 The if/ese statement if-ese exampe if/ese statement is used to decide which of two statements to execute: if (expression) statement1 (or bock) ese statement2 (or bock) expression is evauated If it is true, then statement1 is executed. (statement2 is skipped). If it is fase, then statement2 is executed (statement1 is skipped). statement1 and statement2 are caed branches 13 doube monthysaes; doube price; doube rate; cout << "Enter monthy saes ast month: " ; cin >> monthysaes; cout << "Enter seing price of item: " ; cin >> price; if (monthysaes > 3000) rate =.025; ese rate =.029; doube commission = price * rate; cout << "Commission: $" << commission << end; Enter monthy saes ast month: 3025 Enter seing price of item: 100 Commission: $2.50 14 if-ese structure 4.5 Nested if statements Notice: if (monthysaes > 3000) rate =.025; ese rate =.029; reationa expression is in parentheses NO semi-coon after expression, nor the ese Good stye: indent the statements in each branch!! if-ese is a statement. It can occur as a branch of another if-ese statement. 15 16

Nested if statements Nested if statements if-ese is a statement. It can occur as a branch of another if-ese statement. char borninusa; int age; cout << Were you born in the USA (Y/N)?: ; cin >> borninusa; cout << Pease enter your age: ; cin >> age; if (borninusa == 'Y') if (age >= 35) cout << You quaify to run for President\n ; ese cout << You are too young to run for President\n ; ese cout << You must have been born in the US in order << to run for President << end; 17 if-ese is a statement. It can occur as a branch of another if-ese statement. char borninusa; int age; cout << Were you born in the USA (Y/N)?: ; cin >> borninusa; cout << Pease enter your age: ; cin >> age; if (borninusa == 'Y') if (age >= 35) cout << You quaify to run for President\n ; ese cout << You are too young to run for President\n ; ese cout << You must have been born in the US in order << to run for President << end; 18 Testing a series of conditions Common nested if pattern Decision structure to determine a grade 19 Determine etter grade from test score: If we are in this ese branch, what do we know about the vaue of testscore? if (testscore >= 90) grade = 'A'; ese { if (testscore >= 80) grade = 'B'; ese { if (testscore >= 70) grade = 'C'; ese { if (testscore >= 60) grade = 'D'; ese grade = 'F'; Note the braces are actuay optiona here! 20

4.6 The if/ese if Statement 4.8 Logica Operators Not reay a different statement, just a different way of indenting the nested if statement from the previous side: if (testscore >= 90) grade = 'A'; ese if (testscore >= 80) grade = 'B'; ese if (testscore >= 70) grade = 'C'; ese if (testscore >= 60) grade = 'D'; ese grade = 'F'; Used to create reationa expressions from other reationa expressions: && AND (binary operator) a && b is true ony when both a and b are true OR (binary operator)! a b is true whenever either a or b is true NOT (unary operator) removed braces, put if ( ) on previous ine!a is true when a is fase eiminated nested indentation. 21 22 Exampes int x=6; int y=10; Logica Operators a. x == 5 && y <= 3 fase && fase is fase b. x > 0 && x < 10 true && true is true c. x == 10 y == 10 fase true is true d. x == 10 x == 11 is e.!(x > 0)!true is f.!(x > 6 y == 10)!(fase true) is boo fag; fag = (x > 0 && x < 25); g.!fag h. fag x < 100 23 Logica Operator Precedence! is higher than most operators, so use parentheses: && is higher than int x;!(x < 0 && x > -10) // <, >, &&,! int x, y; boo fag; fag x * 5 >= y + 10 && x == 5 // which op is first? second? etc? && and are ower than arithmetic+reationa operators: parens not usuay needed 24

4.9 Checking Numeric Ranges We want to know if x is in the range from 1 to 10 (incusive) a. if (1 <= x <= 10) //as in math cass cout << YES << end; //THIS DOES NOT WORK IN C++: // ((1<=x) <=10) (assume x is -5) // => ( fase <= 10) // => ( 0<=10 ) is true, but shoud be fase b. if (1 <= x && x <= 10) cout << YES << end; -check: x=0? (1<=0 && 0<=10) => fase && true -check: x=5? (1<=5 && 5<=10) => true && true -check: x=100? (1<=100 && 100<=10) =>?? 25 4.10 Menus Menu-driven program: program controed by user seecting from a ist of actions Menu: ist of choices on the screen Dispay ist of numbered/ettered choices Prompt user to make a seection Test the seection in nested if/ese or switch Match found: execute corresponding code Ese: error message (invaid seection). 26 Sampe menu code 4.11 Vaidating User Input int choice; doube charges; int months = 12; // Dispay the menu and get a choice. cout << "Heath Cub Membership Menu\n\n"; cout << "1. Standard Adut Membership\n"; cout << "2. Chid Membership\n"; cout << "3. Senior Citizen Membership\n"; cout << "Enter your choice: "; cin >> choice; // Respond to the user's menu seection. if (choice==1) { charges = months * 40.0; cout << "The tota charges are $" << charges << end; ese if (choice==2) { charges = months * 20.0; cout << "The tota charges are $" << charges << end; ese if (choice==3) { charges = months * 30.0; cout << "The tota charges are $" << charges << end; ese { cout << ERROR: The vaid choices are 1 through 3. << end; 27 Input vaidation: inspecting input data to determine whether it is acceptabe Invaid input is an error that shoud be treated as an exceptiona case. The program can ask the user to re-enter the data The program can exit with an error message cout << Enter a positive number: ; cin >> x; if (x > 0) { //do something with x here ese { cout << You entered a negative number or 0. << end; cout << The program is ending. << end; 28

4.12 Comparing Characters and Strings Comparing string objects Characters are compared using their ASCII vaues A < B This is true. ASCII vaue of 'A' (65) is ess than the ASCII vaue of B (66) 1 < 2 This is true. ASCII vaue of '1' (49) is ess than the ASCI vaue of '2' (50) Like characters, strings are compared using their ASCII vaues string name1 = "Mary"; string name2 = "Mark"; name1 > name2 // true name1 <= name2 // fase name1!= name2 // true The characters in each string must match exacty in order to be equa Otherwise, use first nonequa character as basis of the comparison ( y > k ) Lowercase etters have higher ASCII codes than uppercase etters, so 'a' > 'Z' name1 < "Mary Jane" // true If a string is a prefix of the other, then it is ess than the other 29 30 4.14 The switch statement Like a nested if/ese, used to seect one of mutipe aternative code sections. tests one integer/char expression against mutipe constant integer/char vaues: switch (expression) { case const1: statements case constn: statements defaut: statements switch statement behavior switch (expression) { case const1: statements case constn: statements defaut: statements expression is evauated to an int/char vaue execution starts at the case abeed with that int/char vaue execution starts at defaut if the int/char vaue matches none of the case abes 31 32

switch statement syntax switch statement exampe switch (expression) { case const1: statements case constn: statements defaut: statements expression must have int/char type const1, constn must be constants! a itera or named constant statements is one or more statements (braces not needed and not recommended!) defaut: is optiona 33 Exampe: int quarter; switch (quarter) { case 1: cout << First ; case 2: cout << Second ; case 3: cout << Third ; case 4: cout << Fourth ; defaut: cout << Invaid choice ; 34 The break Statement Mutipe abes The break statement causes an immediate exit from the switch statement. if ch is a, it fas through to output Option A (then it breaks) Without a break statement, execution continues on to the next set of statements (the next case). Sometimes this is usefu: the textbook has some nice exampes. char ch; switch (ch) { case a : case A : cout << Option A ; case b : case B : cout << Option B ; case c : case C : cout << Option C ; defaut: cout << Invaid choice ; 35 36

4.15 More about bocks and scope The scope of a variabe is the part of the program where the variabe may be used. The scope of a variabe is the innermost bock in which it is defined, from the point of definition to the end of that bock. Note: the body of the main function is just one big bock. 37 Scope of variabes in bocks int main() { doube income; //scope of income is red + bue cout << "What is your annua income? "; cin >> income; if (income >= 35000) { int years; //scope of years is bue; cout << "How many years at current job? "; cin >> years; if (years > 5) cout << "You quaify.\n"; ese cout << "You do not quaify.\n"; Cannot access years ese down here cout << "You do not quaify.\n"; cout << Thanks for appying.\n ; return 0; 38 Variabes with the same name In an inner bock, a variabe is aowed to have the same name as a variabe in the outer bock. When in the inner bock, the outer variabe is not avaiabe (it is hidden). Not good stye: difficut to trace code and find bugs See exampe next side Variabes with the same name int main() { int number; cout << "Enter a number greater than 0: "; cin >> number; if (number > 0) { int number; // another variabe named number cout << "Now enter another number "; cin >> number; cout << "The second number you entered was "; cout << number << end; cout << "Your first number was " << number << end; 39 Enter a number greater than 0: 88 Now enter another number 2 The second number you entered was 2 Your first number was 88 40