Programming1 Lecture 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Making Decisions

LECTURE 5
Computer Programming I
CMPE 121
✓ Relational operators
✓ The if statement
✓ The if/else statement
✓ Nested if statements
✓ The if/else if statement
✓ Flags
✓ Logical operators
✓ The conditional operator
✓ The switch statement
✓ Blocks and variable scope
Tony Gaddis, Starting Out with C++: From Control Structures
through Objects, 8th Edition
✓ Chapter 4 (from page 149 to 226)
Relational operators allow you to compare numeric and char values
and determine whether one is greater than, less than, equal to, or
not equal to another.
Computers are good at performing calculations, but they are also
quite adept at comparing values to determine if one is greater than,
less than, or equal to the other. These types of operations are
valuable for tasks such as examining sales figures, determining profit
and loss, checking a number to ensure it is within an acceptable
range, and validating the input given by a user

4
The question “What is truth?” is one you would expect to find in a
philosophy book, not a C++ programming text.

#include <iostream>
using namespace std;
int main()
{
bool trueValue, falseValue;
int x = 5, y = 10;

trueValue = x < y;
falseValue = y == x;

cout << "True is " << trueValue << endl;


cout << "False is " << falseValue << endl;

return 0;
}
5
The if statement can cause other statements to execute only under
certain conditions. You might think of the statements in a procedural
program as individual steps taken as you are walking down a road. To
reach the destination, you must start at the beginning and take each
step, one after the other, until you reach the destination.

6
In the flowchart, the action “Wear a coat” is performed only when it
is cold outside. If it is not cold outside, the action is skipped. The
action is conditionally executed because it is performed only when a
certain condition (cold outside) exists.
We perform mental tests like these every day. Here are some other
examples:
• If the car is low on gas, stop at a service station and get gas.
• If it’s raining outside, go inside.
• If you’re hungry, get something to eat. 7
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int HIGH_SCORE = 90; // A high score is 90 or greater
int score1, score2, score3; // To hold three test scores
double average; // To hold the average score

cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;

average = (score1 + score2 + score3) / 3.0;


cout << fixed << showpoint << setprecision(1);
cout << "Your average is " << average << endl;

if (average > HIGH_SCORE)


cout << "Congratulations! That's a high score!\n";

return 0;
}

8
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.
So, you must not put a semicolon after the if (expression) portion of
an if statement.

If you inadvertently put a semicolon after the if part, the compiler


will assume you are placing a null statement there. The null
statement is an empty statement that does nothing. This will
prematurely terminate the if statement, which disconnects it from
the statement that follows it.
9
Because of the way that floating-point numbers are stored in
memory, rounding errors sometimes occur. This is because some
fractional numbers cannot be exactly represented using binary. So,
you should be careful when using the equality operator (==) to
compare floating point numbers.
#include <iostream>
using namespace std;
int main()
{
double a = 1.5; // a is 1.5.
double b = 1.5; // b is 1.5.

a += 0.0000000000000001; // Add a little to a.


if (a == b)
cout << "Both a and b are the same.\n";
else
cout << "a and b are not the same.\n";

return 0;
}
10
#include <iostream>
#include <iomanip>
using namespace std;
What if you want an if statement to
int main() conditionally execute a group of
{
int HIGH_SCORE = 90;
statements, not just one line.
int score1, score2, score3;
double average;

cout << "Enter 3 test scores and I will average them: ";
cin >> score1 >> score2 >> score3;

average = (score1 + score2 + score3) / 3.0;


cout << fixed << showpoint << setprecision(1);
cout << "Your average is " << average << endl;

if (average > HIGH_SCORE)


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

return 0;
11
}
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.

As with the if statement, an expression is evaluated. If the expression


is true, a statement or block of statements is executed. If the
expression is false, however, a separate group of statements is
executed.

12
#include <iostream>
using namespace std;
int main()
{
int number;

cout << "Enter a number: ";

cin >> number;

if (number % 2 == 0)
cout << number << " is even.";
else
cout << number << " is odd.";

return 0;
}

13
To test more than one condition, an if statement can be nested inside another if statement.

Sometimes an if statement must be nested inside another if statement. For example, consider a
banking program that determines whether a bank customer qualifies for a special, low interest rate on
a loan. To qualify, two conditions must exist: (1) the customer must be currently employed, and (2) the
customer must have recently graduated from college (in the past two years)

14
#include <iostream>
using namespace std;
int main()
{
char employed, // Currently employed, Y or N
recentGrad; // Recent graduate, Y or N

// Is the user employed and a recent graduate?


cout << "Answer the following questions\n";
cout << "with either Y for Yes or ";
cout << "N for No.\n";
cout << "Are you employed? ";
cin >> employed;
cout << "Have you graduated from college ";
cout << "in the past two years? ";
cin >> recentGrad;
// Determine the user's loan qualifications.
if (employed == 'Y')
{
if (recentGrad == 'Y') //Nested if
{
cout << "You qualify for the special ";
cout << "interest rate.\n";
}
}

return 0;
15
}
16
int testScore; // To hold a numeric test score
cout << "Enter your numeric test score: ";
cin >> testScore; // Get the numeric test score.

// Determine the letter grade.


if (testScore >= 90)
{
cout << "Your grade is A.\n";
}
else
{
if (testScore >= 80)
{
cout << "Your grade is B.\n";
}
else
{
if (testScore >= 70)
{
cout << "Your grade is C.\n";
}
else
{
if (testScore >= 60)
{
cout << "Your grade is D.\n";
}
else
{
cout << "Your grade is F.\n";
}
}
} 17
}
The if/else if statement tests a series of conditions. It is often simpler to test a
series of conditions with the if/else if statement than with a set of nested if/else
statements.

18
#include <iostream>
using namespace std;
int main()
{
int testScore; // To hold a numeric test score
cout << "Enter your numeric test score: ";
cin >> testScore; // Get the numeric test score.

// Determine the letter grade.


if (testScore >= 90)
cout << "Your grade is A.\n";
else if (testScore >= 80)
cout << "Your grade is B.\n";
else if (testScore >= 70)
cout << "Your grade is C.\n";
else if (testScore >= 60)
cout << "Your grade is D.\n";
else
cout << "Your grade is F.\n";

return 0;
} 19
A flag is a Boolean or integer variable that signals when a condition
exists.
A flag is typically a bool variable that signals when some condition exists in the
program. When the flag variable is set to false, it indicates that the condition
does not exist. When the flag variable is set to true, it means the condition does
exist.

bool salesQuotaMet = false;

if (sales >= QUOTA_AMOUNT)


salesQuotaMet = true;
else
salesQuotaMet = false;

if (salesQuotaMet)
cout << "You have met your sales quota!\n";

20
Logical operators connect two or more relational expressions into one or
reverse the logic of an expression.

21
#include <iostream>
using namespace std;
int main()
{
int username, password;

cout << "Enter username: ";


cin >> username;
cout << "Enter password: ";
cin >> password;

if (username == 123 && password == 555)


{
cout << "Logged in" << endl;
}
else
{
cout << "Access Denied!" << endl;
}

cout << "Thank you" << endl;

return 0;
22
}
#include <iostream>
using namespace std;
int main()
{
int username, password;

cout << "Enter username: ";


cin >> username;
cout << "Enter password: ";
cin >> password;

if (username != 123 && password != 555)


{
cout << "Access Denied! " << endl;
}
else
{
cout << " Logged in" << endl;
}

cout << "Thank you" << endl;

return 0;
23
}
#include <iostream>
using namespace std;
int main()
{
int username, password;

cout << "Enter username: ";


cin >> username;
cout << "Enter password: ";
cin >> password;

if (!(username == 123 && password == 555))


{
cout << “Access Denied!" << endl;
}
else
{
cout << “Logged in" << endl;
}

cout << "Thank you" << endl;

return 0;
24
}
Relational operators can also be used to compare characters and string
objects
#include <iostream>
using namespace std;
int main()
{
char ch;
// Get a character from the user.
cout << "Enter a digit or a letter: ";
ch = cin.get();

// Determine what the user entered.


if (ch >= '0' && ch <= '9’)
cout << "You entered a digit.\n";
else if (ch >= 'A' && ch <= 'Z’)
cout << "You entered an uppercase letter.\n";
else if (ch >= 'a' && ch <= 'z’)
cout << "You entered a lowercase letter.\n";
else
cout << "That is not a digit or a letter.\n";

return 0;
}
25
The switch statement lets the value of a variable or expression determine where
the program will branch.
A branch occurs when one part of a program causes another part to execute. The
if/else if statement allows your program to branch into one of several
possible paths. It performs a series of tests (usually relational) and branches when
one of these tests is true.
The switch statement is a similar mechanism. It, however, tests the value of an
integer expression and then uses that value to determine which set of statements
to branch to.

26
#include <iostream>
using namespace std;
int main()
{
char choice;

cout << "Enter A, B, or C: ";


cin >> choice;
switch (choice)
{
case 'A': cout << "You entered A.\n";
break;
case 'B': cout << "You entered B.\n";
break;
case 'C': cout << "You entered C.\n";
break;
default: cout << "You did not enter A, B, or C!\n";
}

return 0;
}
27
The scope of a variable is limited to the block in which it is defined. C++ allows you
to create variables almost anywhere in a program.
#include <iostream>
using namespace std;
int main()
{
// Define a variable named number.
int number;

cout << "Enter a number greater than 0: ";


cin >> number;
if (number > 0)
{
int number; // Another variable named number.
cout << "Now enter another number: ";
cin >> number;
cout << "The second number was " << number << endl;
}
cout << "Your first number was " << number << endl;

return 0;
}
28

You might also like