CS208 C++ Programming Part 2 7/11/2016

advertisement
CS208
C++ Programming
Part 2
7/11/2016
1
Boolean Expressions
A boolean expression is a condition in which
a relational operator tests the relationship
between two expressions and returns a
boolean (TRUE or FALSE) result.

Syntax for condition:
(<expr> <relop> <expr>)
2
Algebraic vs C++
Equality & Relational Operators
Algebraic
operator
C++
Example
operator of C++
condition
Meaning of
C++ condition
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>
<
>=
<=
x
x
x
x
x is greater than y
x is less than y
x is greater than or equal to y
x is less than or equal to y
Equality operators
=

Relational operators
>
<


> y
< y
>= y
<= y
NOTE that “=“ is for assignment and “==“ is for equality comparison
3
Decisions

Boolean expressions are used to make decisions
The expression is evaluated to TRUE or FALSE
Example:
 Given the boolean expression:
( Num < 5 )
 When Num = 1,
the expression evaluates to TRUE
 When Num = 25,
the expression evaluates to FALSE


4
The if Statement
Syntax:
One Alternative
if (condition)
statementT;
//do the statement if condition is TRUE
Two Alternatives
if (condition)
statementT ;
else
statementF ;
// do only this if TRUE
// do only this if FALSE
5
One Alternative if Statement
if is a C++
reserved word
The condition must be a boolean expression.
It must be enclosed in parentheses.
It must evaluate to either true or false.
if ( condition )
statement;
The statement is indented.
If the condition is TRUE, the statement is executed.
If it is FALSE, the statement is skipped.
6
One Alternative
if Control Structure
English: if student’s grade is greater than 60, print "Passed"
Grade
true
over 60?
print "Passed"
false
Code:
if (grade > 60)
cout << "Passed";
7
One Alternative if Examples
if (Age < 18)
cout << "Minor";
if (Divisor != 0)
Answer = Num / Divisor;
if (Num < 10)
Num = Num + 1;
8
One Alternative if
Program Description



Modify previous Age program (from part 1)
to take into account the current MONTH, as
well as the current YEAR.
Read in the user’s birth MONTH and birth
YEAR
Calculate and display the user’s age
9
Age Program Design

What are the program inputs?


needs variables
What are the program outputs?


Year and Month of Birth
Age
needs a variable
Are there any values the programmer will set?

Current year and month
needs constants
10
Age Program Algorithm

Pseudocode:

Prompt for and read in user’s year of birth

Prompt for and read in user’s month of birth

Compute user’s age

If birth month has not yet passed,


Subtract one from user’s age
Display user’s age
11
Age Program Code
#include <iostream.h>
void main()
{
const int CurYr = 2005;
const int CurMon = 9;
int BirthYr, BirthMon, Age;
cout << "Enter 4-digit year of birth: ";
cin >> BirthYr;
cout << "Enter numeric month of birth: ";
cin >> BirthMon;
Age = CurYr - BirthYr;
if (BirthMon > CurMon)
Age = Age – 1;
cout << "Your age is " << Age;
}
12
Age Program Explanation (1/3)
const int CurYr = 2005;
const int CurMon = 9;
/* declare two constants,
CurYr and CurMon */
int BirthYr, BirthMon, Age;
/* declare 3 integer variables,
BirthYr, BirthMon and Age */
Memory
Age:
BirthYr:
BirthMon:
CurYr: 2005
CurMon:
10
13
Age Program Explanation (2/3)
cout << "Enter 4-digit year of birth: ";
Screen:
cin >> BirthYr;
/* display prompt, and
read value entered into BirthYr */
Enter 4-digit year of birth: 1962
Enter numeric month of birth: 10
cout << "Enter numeric month of birth: ";
cin >> BirthMon;
Memory
/* display prompt, and
read value entered into BirthMon */
Age:
BirthYr: 1962
BirthMon:
10
CurYr: 2005
CurMon:
9
14
Age Program Explanation (3/3)
Age = CurYr - BirthYr;
/* subtract value in BirthYr from value in
CurYr; store result into variable Age */
if (BirthMon > CurMon)
Age = Age – 1;
Memory
Age:
43
42
BirthYr: 1962
BirthMon:
10
CurYr: 2005
CurMon:
9
/* test to see if BirthMon is greater than CurMon
if so, subtract 1 from value in variable Age */
Screen:
cout << "Your age is " << Age;
Enter 4-digit year of birth: 1962
// display message and calculated Age
Enter numeric month of birth: 10
Your age is 42
15
Two Alternative if Statement
The condition must be a boolean expression.
It must be enclosed in parentheses.
It must evaluate to either true or false.
if ( condition )
statementT;
else
statementF;
If the condition is TRUE, only statementT is executed.
If it is FALSE, only statementF is executed.
16
Two Alternative
if-else Control Structure
English: if students' grade is greater than 60, print "Passed“,
otherwise print “Failed”
true
print “Passed”;
Grade
false
over 60?
print “Failed”
Code: if (grade > 60)
cout << "Passed";
else
cout << "Failed";
17
Two alternative if Examples
if (Num >= 0)
cout << "Positive";
else
cout << "Negative";
if (Temp < 50)
Heater = 1;
else
Heater = 0;
if (MorD == 'M')
cout << "Hi Mom!";
else
cout << "Hi Dad!";
18
Two Alternative
Program Example Description


At a gas station, there are two kinds of gas:
unleaded and premium. Unleaded is $1.89
per gallon, and premium is $1.98 per gallon.
Design a program to read the type of gas and
number of gallons from the user. The
program should display the customer’s total
bill for the gas.
19
Gas Program Design

What are the program inputs?



Total cost
needs a variable
Are there any values the programmer will set?



needs a variable
needs a variable
What are the program outputs?


Type of gas purchased
Number of gallons purchased
Unleaded price per gallon
Premium price per gallon
needs a constant
needs a constant
How do we calculate the output value?

Total cost = price per gallon X number of gallons formula
20
Gas Program Algorithm

Pseudocode:
 Prompt for and read in Type of Gas
 Prompt for and read in Number of Gallons
 If Type of Gas is Unleaded,
 Compute Total using Unleaded Price
 Otherwise
 Compute Total using premium Price
 Display Total Cost
21
Gas Program
Example Code
#include <iostream.h>
void main()
{
const double unlead = 1.89;
const double prem = 1.98;
char gas_type;
double gallons, total;
cout << "What type of gas (u/p)?: ";
cin >> gas_type;
cout << "How many gallons? ";
cin >> gallons;
if (gas_type == 'u')
total = unlead * gallons;
else
total = prem * gallons;
cout << "Total is " << total;
}
22
Gas Program Explanation (1/3)
const double unlead = 1.89;
const double prem = 1.98;
Memory
/* declare two constants */
char gas_type;
double gallons, total;
gas_type:
gallons:
total:
ulead:
prem:
1.89
1.98
/* declare one character variable
and two double variables */
23
Gas Program Explanation (2/3)
cout << " What type of gas (u/p)? ";
cin >> gas_type;
Screen:
/* display prompt, and
read value entered into gas_type */
What type of gas (u/p)? p
How many gallons? 11.3
Memory
cout << " How many gallons? ";
gas_type:
‘p’
cin >> gallons;
/* display prompt, and
read value entered into gallons */
gallons: 11.3
total:
ulead: 1.89
prem: 1.98
24
Gas Program Explanation (3/3)
if (gas_type == 'u')
total = unlead * gallons;
else
total = prem * gallons;
/* Test condition (gas_type == ‘u’)
In the example, the condition is FALSE, so
the else statement is executed:
Multiply value in constant prem by value
in variable gallons and store result in
variable total */
Memory
gas_type:
‘p’
gallons: 11.3
total: 22.374
ulead: 1.89
prem: 1.98
Screen:
What type of gas (u/p)? p
How many gallons? 11.3
Total is 22.374
cout << "Total is " << total;
// display message and the value in variable total
25
Gas Program Modification

The gas program output was:
Total is 22.374


But dollars and cents should be rounded to 2
decimal places
Add the following 2 lines BEFORE the cout output
statement:
cout.setf(ios::fixed);
cout.precision(2);

The output will now be:
Total is 22.37
26
if Exercise
Exercise:
Write a program that reads in 2 integers and outputs
the smallest.
Sample Run:
Enter 2 numbers: 99 8
Smallest number is 8
(Answer on next slide
– try writing program yourself before looking at the
answer)
27
If Exercise Answer
#include <iostream.h>
void main()
{
int Num1, Num2;
cout << "Enter 2 numbers: ";
cin >> Num1;
cin >> Num2;
if (Num1 < Num2)
cout << "Smallest number is " << Num1;
else
cout << "Smallest number is " << Num2;
}
28
Compound Statements



A compound statement is more than one
statement enclosed in { }
Branches of if-else statements often need to
execute more that one statement
Example:
if (boolean expression)
{
true statements
}
else
{
false statements
}
29
Loop Statements

Loop statements allow us to execute a program
statement (or statements) multiple times



They are often simply referred to as loops
Like conditional if statements, they are
controlled by boolean expressions
C++ has four kinds of loop statements, but in this
class we will study only ONE of them:

the while loop
30
The conditional while Loop
Syntax: while (boolean-expression)
{
statement1;
:
statementN;
}
NOTE:
- The curly braces {} are not needed if there is
only ONE statement in the loop body
31
The while Statement
while is a C++
reserved word
The condition must be a boolean expression.
It must be enclosed in parentheses.
It must evaluate to either true or false.
while ( condition )
{
statement1;
:
statementN;
}
The statement(s) must be indented.
If the condition is TRUE, the statement(s) within the curly braces are executed.
If FALSE, the program skips to the statement FOLLOWING the loop statement(s).
32
while control structure
English:
while the Amount is under 100,
add 1 to the amount
Amount
true
under 100?
Add 1 to Amount
false
Code:
while (Amount < 100)
Amount = Amount + 1;
33
while Loop Example
Example #1:
Display a count by two’s to 100.
#include <iostream.h>
void main()
{
int Num = 2;
while (Num <= 100)
{
cout << Num << endl;
Num = Num + 2;
}
cout << "Done!";
}
34
Count by Twos Explanation (1/9)
int Num = 2;
/* declare an integer variable, Num,
and initialize its value to 2 */
Memory
Num:
2
35
Count by Twos Explanation (2/9)
while (Num <= 100)
// Test the condition (Num <= 100)
Memory
Num:
2
/* In the example Num is currently 2,
so the condition is TRUE, meaning we will
execute the statements between the curly braces. */
36
Count by Twos Explanation (3/9)
Execute the statements within the curly braces:
cout << Num << endl;
/* Display value in variable Num to screen
Then output a newline, so the next
output will appear on the next line*/
Num = Num + 2;
Num:
/* Add 2 to the value currently stored in
variable Num.
Store the result back into the variable Num*/
Screen:
2
Memory
2
4
37
Count by Twos Explanation (4/9)
Loop back to the top of the while loop:
while (Num <= 100)
// Test the condition (Num <= 100)
Memory
Num:
/*
4
In the example Num is currently 4,
so the condition is still TRUE,
meaning we will execute the statements
between the curly braces again */
38
Count by Twos Explanation (5/9)
Execute the statements within the curly braces:
cout << Num << endl;
/* Display value in variable Num to screen
Then output a newline, so the next
output will appear on the next line*/
Num = Num + 2;
Num:
/* Add 2 to the value currently stored in
variable Num.
Store the result back into the variable Num*/
Screen:
2
4
Memory
4
6
39
Count by Twos Explanation (6/9)
The program will continue looping back to the top of the
while loop, testing the condition and executing the
statements, UNTIL the condition evaluates to FALSE.
So on the LAST loop:
Memory
while (Num <= 100)
// Test the condition (Num <= 100)
Num:
/* In the example Num is currently 100,
so the condition is still TRUE,
meaning we will execute the statements
between the curly braces again */
100
40
Count by Twos Explanation (7/9)
Execute the statements within the curly braces:
cout << Num << endl;
/* Display value in variable Num to screen
Then output a newline, so the next
output will appear on the next line*/
Screen:
2
4
6
:
96
98
100
Num = Num + 2;
/* Add 2 to the value currently stored in
Num:
variable Num.
Store the result back into the variable Num*/
Memory
100
102
41
Count by Twos Explanation (8/9)
Loop back to the top of the while loop:
while (Num <= 100)
// Test the condition (Num <= 100)
Memory
Num:
102
/* In the example Num is currently 102,
so the condition is now FALSE,
meaning we will SKIP the statements
between the curly braces and exit the loop */
42
Count by Twos Explanation (9/9)
Execute the statement after the while loop:
Screen:
cout << "Done!";
// Display Done! to the screen
2
4
6
:
96
98
100
Done!
Program Terminates.
43
Loop Example #2
Example #2: Error check a positive number is entered.
int Num;
cout << "Enter a positive number: ";
cin >> Num;
while (Num < 0)
{
cout << "Invalid entry. Try Again." << endl << endl;
cout << "Positive number: ";
cin >> Num;
}
cout << "You entered " << Num;
44
Example #2 Output
Enter a positive Number: -1
Invalid entry. Try again.
Positive Number: -3
Invalid entry. Try again.
Positive Number: 5
You entered 5
45
while loop conditions


If the condition of a while loop is initially
false, the loop statements in the loop are
never executed
Therefore, the body of a while loop will
execute zero or more times
46
Example #2 Output Revisited
Enter a positive Number: 20
You entered 20
In this case, the while loop condition:
(num < 0)
was initially FALSE because the user entered a
positive number as the first number.
So the while loop statements did NOT execute.
47
Infinite Loops


The statements of a while loop must do
something to eventually make the condition
evaluate to false
If it doesn’t, you will have an infinite loop,
which will execute until the user interrupts
the program (with Ctrl-C )


This is a common type of logical error
You should always double check to ensure
that your loops will eventually terminate!
48
while Loop Exercise
Exercise:
Write a WHILE loop that will add a series of
positive integers as they are entered by the user.
Stop adding and display the total when the user
enters a negative number.
Sample Run:
Number? 10
Number? 20
Number? -1
Total is 30
(Answer on next slide – Try first, then view answer)
49
while Loop Exercise Solution
int Num, Sum;
Sum = 0;
cout << "Number? ";
cin >> Num;
while (Num >= 0)
{
Sum = Sum + Num;
cout << endl << "Number? ";
cin >> Num;
}
cout << endl << "Total is " << Sum;
50
Debugging

Bug


A mistake in a program
Debugging


Eliminating mistakes in programs
Term originated when a moth caused a
failed relay in the Harvard Mark 1
computer.
51
Syntax and Semantics




The syntax rules of a programming language
define how we can put symbols together to make
a valid program
The semantics of a program statement define
what a statement means (its purpose or role in a
program)
A program that is syntactically correct is not
necessarily logically (semantically) correct
A program will always do what we tell it to do,
not what we meant to tell it to do
52
Program Errors

Compile-Time Errors

The compiler will find most of the problems
with syntax and other basic issues



Error messages may not always show correct
location of errors
If compile-time errors exist, an executable
version of the program is not created
Compiler-time errors will be listed under the
compiler tab in the window below your code
53
A syntax error is detected by the
Compiler. A semicolon is missing
at the end of this statement.
A semi-colon is missing at the
end of this statement.
Compiler detects a syntax error.
54
Program Errors

Runtime Errors

A problem can occur during program execution


such as trying to divide by zero
which causes a program to terminate abnormally
(run-time errors)
55
Runtime error during execution
causes program to terminate
abnormally.
56
Program Errors

Logical Errors
- A program runs, but produces incorrect results
 Most difficult to diagnose
Logical error The square of 5 should be 25,
not 10
57
Programming

Your job as a programmer is to:



Design the program
Write the code
Debug the code to eliminate:
 compile-time errors
 run-time errors and
 logical errors
58
Download