+ All Categories
Home > Documents > Chapter 4: Making Decisions. Resource: Starting Out with C++, Third Edition, Tony Gaddis 4.1...

Chapter 4: Making Decisions. Resource: Starting Out with C++, Third Edition, Tony Gaddis 4.1...

Date post: 02-Jan-2016
Category:
Upload: stewart-caldwell
View: 237 times
Download: 0 times
Share this document with a friend
Popular Tags:
28
Chapter 4: Making Decisions
Transcript

Chapter 4: Making Decisions

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4.1 Relational Operators

• Relational operators allow you to compare numeric values and determine if one is greater than, less than, equal to, or not equal to another.

• Chars are also considered numeric values.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Programs You’ve Written

• Gather input from the user.• Perform one or more

calculations.• Display the results on the

screen.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Computers

• Good at performing calculations.• Adept to comparing values to

determine if one is greater than, less than, or equal to, the other.

• The computer can assist with:– Examining sales figures– Determining profit and loss– Checking a number to ensure it is

within an acceptable range– Validating the input given by the

user

Table 4-3: Relational Expressionsand Their True or False Values

Expression Value

X < Y False, because X is not less than Y .

X > Y True, because X is greater than Y .

X > = Y True, because X is greater than or equal to Y .

X < = Y False, because X is not less than or equal to Y .

Y != X True, because Y is not equal to X .

In C++, relational expressions represent true states with the number 1 and false states with the number 0.

Table 4-5: Examples of if Statements

Statements Outcome

if (H o u rs > 4 0 ) O v e rT im e = 1 ;

Assigns 1 to O v erT im e only when H o u rs is greater than 40

if (V a lu e > 3 2 ) co u t < < " In v a lid n u m b er \n " ;

Displays the message “Invalid number” only when V a lu e is greater than 32

if (O v e rT im e = = 1 ) P ay R a te * = 2 ;

Multiplies P ay R a te by 2 only when O v erT im e is equal to 1

Here is the general format of the if statement:If (expression) statement;

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Be Careful With Semicolons

• Semicolons do not mark the end of a line, but the end of a complete C++ statement.

• The if statement isn’t complete without the conditionally executed statement that comes after it.

• Therefore, you do not put a semicolon after the if (expression) portion of an if statement.

if (expression) No semicolon goes here

statement; Semicolon goes here

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-3

//This program demonstrates how a misplaced semicolon//prematurely terminates an if statement.#include <iostream.h>

void main(void){

int x = 0, y = 10;cout << “x is " << x << " and y is " << y << endl;if (x > y); // misplaced semicolon!

cout << “x is greater than y\n"; // Always executed

}

Program OutputX is 0 and Y is 10

X is greater than Y

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Comparing Floating Point Numbers

• You should be careful when using the equality operator (==) to compare floating point values. Because of round-off errors.

• A number that should be mathematically equal to another might not be.

• To prevent errors like this, stick with greater-than and less-than comparisons with floating point numbers.

Refer to Program 4-4

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4.4 Expanding the if Statement

• The if statement can conditionally execute a block of statement enclosed in braces.

if (expression)

{

statement;

statement;

// Place as many statements here as necessary.

}

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-7 Continued

cout.precision(1);cout.setf(ios::showpoint | ios::fixed);cout << "Your average is " << average << endl;if (highScore){

cout << "Congratulations!\n";cout << "That's a high score.\n";cout << "You deserve a pat on the

back!\n";}

}

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Don’t Forget the Braces!

• If you intend to execute a block of statements with an if statement, don’t forget the braces.

• Without the braces, the if statement only executes the very next statement.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4.5 The if/else Statement

• The if/else statement will execute one group of statements if the expression is true, or another group of statements if the expression is false.

• The if/else statement is an expansion of the if statement. Here is the format:

if (expression)

statement or block of statements;else

statement or block of statements;

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-9// This program uses the modulus operator to determine// if a number is odd or even. If the number is evenly// divided by 2, it is an even number. A remainder// indicates it is odd.

#include <iostream.h>

void main(void){

int number;cout << "Enter an integer and I will tell you if it\n";cout << "is odd or even. ";cin >> number;if (number % 2 == 0)

cout << number << " is even.\n";else

cout << number << " is odd.\n";}

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4-9 Program Output with Example Input

Enter an integer and I will tell you if it is odd or even. 17 [Enter]

17 is odd.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4.6 The if/else if Construct

• The if/else if statement is a chain of if statements. The perform their tests, one after the other, until one of them is found to be true.

If (expression) statement or block of statements;else if (expression) statement or block of statements;// put as many else it’s as needed hereelse if (expression) statement or block of statements;

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-11// This program uses an if/else if statement// to assign a letter grade (A, B, C, D, or F) // to a numeric test score.#include <iostream.h>

void main(void){

int testScore;char grade;

cout << "Enter your numeric test score and I will\n";cout << "tell you the letter grade you earned: ";cin >> testScore;

Resource: Starting Out with C++, Third Edition, Tony Gaddis

if (testScore < 60)grade = 'F';

else if (testScore < 70)grade = 'D';

else if (testScore < 80)grade = 'C';

else if (testScore < 90)grade = 'B';

else if (testScore <= 100)grade = 'A';

cout << "Your grade is " << grade << ".\n";

}

4-11 Program Continued

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4-11 Program Output with Example Input

Enter your test score and I willtell you the letter grade you earned:

88 [Enter]

Your grade is B.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-13//This program uses an if/else if statement to//assign a letter grade ( A, B, C, D, or F )//to a numeric test score.#include<iostream.h>

void main(void){

int testScore;cout << "Enter your test score and I will tell you\n";cout << "the letter grade you earned: ";cin >> testScore;if (testScore < 60){

cout << "Your grade is F.\n"; cout << "This is a failing grade. Better see your "; cout << "instructor.\n"; } else if (testScore < 70) { cout << "Your grade is D.\n"; cout << "This is below average. You should get "; cout << "tutoring.\n"; }

Resource: Starting Out with C++, Third Edition, Tony Gaddis

else if (testScore < 80) { cout << "Your grade is C.\n"; cout << "This is average.\n"; } else if(testScore < 90) { cout << "Your grade is B.\n"; cout << "This is an above average grade.\n"; } else if (testScore <= 100) { cout << "Your grade is A.\n"; cout << "This is a superior grade. Good work!\n"; }}

4-13 Program Continued

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4-13 Program Output with Example Input

Enter your test score and I will tell

you the letter grade you earned: 94 [Enter]

Your grade is A.

This is a superior grade. Good work!

Resource: Starting Out with C++, Third Edition, Tony Gaddis

4.7 Using a Trailing else

• A trailing else, placed at the end of an if/else if statement, provides default action when none of the if’s have true expressions.

Table 4-6: Lists C++’s Logical Operators

Operator Meaning Effect

& & AND Connects two expressions into one. Bothexpressions must be true for the overallexpression to be true.

|| OR Connects two expressions into one. One orboth expressions must be true for the overallexpression to be true. It is only necessary forone to be true, and it does not matter which.

! NOT The ! operator reverses the “truth” of anexpression. It makes a true expression false,and a false expression true.

Resource: Starting Out with C++, Third Edition, Tony Gaddis

cout << "Have you graduated from college "; cout << "in the past two years? "; cin >> recentGrad; if (employed == 'Y‘ && recentGrad == 'Y') // &&

Operator { cout << "You qualify for the special "; cout << "interest rate.\n"; } else { cout << "You must be employed and have \n"; cout << "graduated from college in the\n"; cout << "past two years to qualify.\n"; }}

4-18 Program Continued

Table 4-9: Shows a Truth Table for the 1 Operator

Expression !(Expression)

True False (0)

False True (1)

Resource: Starting Out with C++, Third Edition, Tony Gaddis

Program 4-20//This program asks the user for his annual income and //the number of years he has been employed at his current job. //The ! operator reverses the logic of the expression in the if/else //statement.#include <iostream.h>

void main(void){

float income; int years;cout << "What is your annual income? ";cin >> income;cout << "How many years have you worked at " << "your current job? ";cin >> years;if (!(income >= 35000 || years > 5)) // Uses the ! Logical operator{

cout << "You must earn at least $35,000 or have\n";cout << "been employed for more than 5 years.\n";

}else

cout << "You qualify.\n";

}

Table 4-10: Precedence of Logical Operators

!

&&

||


Recommended