1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how.

Slides:



Advertisements
Similar presentations
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
Advertisements

June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Chapter 6 Horstmann Programs that make decisions: the IF command.
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)
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Computer Science 1620 Programming & Problem Solving.
Chapter 5: Control Structures II (Repetition)
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Fundamentals of Python: First Programs
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Chapter 02 (Part III) Introduction to C++ Programming.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
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.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
If Statement if (amount
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
ICT Introduction to Programming Chapter 4 – Control Structures I.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 October 22, The If Statement Programs make decisions If(condition){ Statement(s); } Condition  boolean expression Evaluates to either.
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 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Branching statements.
Chapter 5: Control Structures II (Repetition)
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.
Program Control Flow: Making Decision
Chapter 4: Making Decisions.
Chapter 2 Assignment and Interactive Input
Control Structures II (Repetition)
Chapter 4: Control Structures I (Selection)
3 Control Statements:.
Chapter 4 Selection.
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Let’s all Repeat Together
2.6 The if/else Selection Structure
Chapter 5: Control Structures II (Repetition)
Repetition Statements (Loops) - 2
Presentation transcript:

1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how to compare integers, floating- point numbers, and strings  To develop strategies for processing input and handling errors  To understand the Boolean data type  To avoid infinite loops and off-by-one errors

2 The if Statement ► The if statement is used to implement a decision. ► It has two parts: a test and a body. Example: if (area < 0) cerr << "Error: Negative area.\n"; cerr << "Error: Negative area.\n"; ► Multiple statements can be grouped together in a block statement by enclosing them in braces { }: Example: if (area < 0) { cerr << "Error: Negative area.\n"; cerr << "Error: Negative area.\n"; return 1; return 1;}

3 (Syntax 4.1 : if Statement) ► General format of syntax of if_statement: if ( ) if ( ) ► Example: if (x >= 0) y = sqrt(x); ► Purpose:  To xecute the statement if the condition is true.  In the example, it executes the assignment if the condition (x>=0) is true.

4 (Syntax 4.2 : Block Statement) ► Block Statement: group of one of more statements considered as one statement. ► General Syntax: { statement1 statement2 statement2... statementn } statementn } ► Example: { double length = sqrt(area); cout << area << "\n"; } ► Purpose: To group several statements into a block that can be controlled by another statement.

5 The if Statement (area1.cpp) 01: #include 01: #include 02: #include 02: #include 03: #include 03: #include 04: 05: using namespace std; 06: 07: int main() { 09: double area; 10: cout << "Please enter the area of a square: "; 11: cin >> area; 12: if (area < 0) { 14: cout << "Error: Negative area.\n"; 15: return 1; 16: } 18: /* now we know that area is >= 0 */ 20: double length = sqrt(area); 21: cout << "The side length of the square is " 22: << length << "\n"; 24: return 0; 25: }

6 The if/else Statement ► The if/else consists of a condition of two alternatives.  The first alternative is performed if the condition is true.  The second alternative is performed if the condition is false. ► Example: if (area >= 0) cout << "The side length is " cout << "The side length is " << sqrt(area) << "\n"; << sqrt(area) << "\n";else cout << "Error: Negative area.\n"; cout << "Error: Negative area.\n"; ► The if/else statement is a better choice than a pair of if statements with complementary conditions. Example: (not a good practice) if (area >= 0) cout << "The side length is " << sqrt(area) cout << "The side length is " << sqrt(area) << "\n"; << "\n"; if (area < 0) cout << "Error: Negative area.\n"; cout << "Error: Negative area.\n";

7 (Syntax 4.3 : if/else Statement) ► General syntax of if/else Statement if ( ) else else ► Example: if (x >= 0) y = sqrt(x); y = sqrt(x);else cout << "Bad input\n"; cout << "Bad input\n";Purpose: Execute the first statement if the condition is true, or the second statement if the condition is false.

8 Example Program (if/else) 01: #include 01: #include 02: #include 02: #include 03: #include 03: #include 04: 05: using namespace std; 06: 07: int main() { 07: int main() { 09: double area; 10: cout << "Please enter the area of a square: "; 11: cin >> area; 12: if (area >= 0) 13: cout << "The side length is " << sqrt(area) << "\n"; << sqrt(area) << "\n"; 15: else 16: cout << "Error: Negative area.\n"; 17: 18: return 0; 19: } 19: }

9 Relational Operators C++DescriptionExampleNotes > greater than greater thana>5 >= greater than or equal to x >= 5 Be careful to not write =>. Remember that the symbols appear in the order you say them < less than x < 10 <= less than or equal to x <= 100 Be careful to not write =<. Remember that the symbols appear in the order you say them == equal to a == 5 Don't confuse with =, which is assignment. != not equal a != 5 The ! is supposed to be the line that "crosses through" the equal sign.

10 Relational Operators(comparing strings) ► The relational operators listed above can also be used to compare strings using lexicological comparison. ► Examples:  "car" is less than "cargo"  "cargo" is less than "cathode" car cargo

11 Input Validation ► Input validation is an application of a conditional statement to verify if the user has entered valid input. ► Example: double area; cin >> area; If user types "five" and hits return!, it produces an input error (causing cin to fail). If user types "five" and hits return!, it produces an input error (causing cin to fail). ► After every input a good program will test: if (cin.fail()) ► The actual input should also be validated, even if the type is correct. Example: if (area < 0) ► Other strategies:  if (cin) /* the stream did not fail */ else /* the stream failed */  if (cin >> x)...

12 Input Validation (area3.cpp) 01: #include 02: #include 03: #include 04: 05: using namespace std; 06: 07: int main() { 09: double area; 10: cout > area; 12: 13: if (cin.fail()){ 15: cout 02: #include 03: #include 04: 05: using namespace std; 06: 07: int main() { 09: double area; 10: cout > area; 12: 13: if (cin.fail()){ 15: cout << "Error: Bad input\n"; 16: return 1; 17: } 18: 19: if (area < 0){ 21: cout << "Error: Negative area.\n"; 22: return 1; 23: } 25: cout << "The side length is " << sqrt(area) << "\n"; 27: return 0; 27: return 0; 28: } 28: }

13 Simple Loops ► A loop is a block of code (loop body) that can be performed repeatedly. ► A loop is controlled by a condition that is checked before or after each repetition. ► The while statement makes a check before each execution of the loop body. Example: /* Number of year for an investment to double */ double */year=0; while (balance < 2*initial_balance){ balance = balance*(1+rate/100); year++; }

14 (Syntax 4.4 : while Statement) ► General format or syntax of while statement: (condition) while(condition) statement statement  The loop body is a simple or block statement. ► Example: while (x >= 10) x = sqrt(x); x = sqrt(x);Purpose: Execute the statement while the condition remains true.

15 Processing a Sequence of Inputs (Sentinels) ► Whenever you read a sequence of input values, you need to have some method of terminating the input. ► A value used to signal termination is called a sentinel. ► Sentinels only work if there is some restriction on the input values. ► Common sentinel values are 0 or -1.

16 Processing a Sequence of Inputs (sentinel.cpp) 01: #include 02: 03: using namespace std; 04: 05: int main() { 07: double sum = 0; 08: int count = 0; 09: bool more = true; 10: double salary = 0; 11: while (more) { 13: cout > salary; 15: if (salary != -1) { 17: sum = sum + salary; 18: count++; 19: } else 01: #include 02: 03: using namespace std; 04: 05: int main() { 07: double sum = 0; 08: int count = 0; 09: bool more = true; 10: double salary = 0; 11: while (more) { 13: cout > salary; 15: if (salary != -1) { 17: sum = sum + salary; 18: count++; 19: } else more = false; more = false; 20: } 21: if (count > 0) 22: cout 0) 22: cout << "Average salary: " << sum / count << "\n"; 23: return 0; 24: }

17 Processing a Sequence of Inputs (Causing the Stream to Fail) ► When reading input from the console, you can close the stream manually.  Ctrl + Z in Windows (press both keys simultaneously)  Ctrl + D in UNIX ► Reading from a closed stream causes the stream to enter the failed state.

18 Processing a Sequence of Inputs (maxtemp.cpp) 01: #include 02: 03: using namespace std; 04: 05: int main() { 07: double next; 08: double highest; 09: 10: cout > next) // reads first value 12: highest = next; 13: else { 15: cout > next) { 21: if (next > highest) 22: highest = next; 23: } 25: cout 02: 03: using namespace std; 04: 05: int main() { 07: double next; 08: double highest; 09: 10: cout > next) // reads first value 12: highest = next; 13: else { 15: cout > next) { 21: if (next > highest) 22: highest = next; 23: } 25: cout << "The highest temperature is " << highest << "\n"; << highest << "\n"; 27: return 0; 27: return 0; 28: } 28: }

19 Using Boolean Variables ► The bool type can hold exactly two values, denoted false and true. ► Boolean variables are named after George Boole ( ), a pioneer in the study of logic. ► Example: bool more = true; while (more) { cin >> next; if (cin.fail()) more = false; more = false; else { // process next // process next …. …. }} ► Don't: while(more == false) /* don't */ while(more != false) /* don't */