Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 19 Using Boolean Variables ► The bool type can hold exactly two values, denoted false and true. ► Boolean variables are named after George Boole (1815-1864), 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 */


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

Similar presentations


Ads by Google