Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Chapter 2
C++ Basics
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Overview
2.1 Variables and Assignments
2.2 Input and Output
2.3 Data Types and Expressions
2.4 Simple Flow of Control
2.5 Program Style
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 3
2.1
Variables and Assignments
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Variables and Assignments
◼ Variables are like small blackboards
◼ We can write a value in them
◼ We can change the value
◼ We can erase the value
◼ C++ variables are names for memory locations
◼ We can write a value in them
◼ We can change the value stored there
◼ We cannot erase the memory location
◼ Some value is always there
Display 2.1
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 5
Identifiers
◼ Variables names are called identifiers
◼ Choosing variable names
◼ Use meaningful names that represent data to
be stored
◼ First character must be
◼ a letter
◼ the underscore character
◼ Remaining characters must be
◼ letters
◼ numbers
◼ underscore character
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 6
Keywords
◼ Keywords (also called reserved words)
◼ Are used by the C++ language
◼ Must be used as they are defined in
the programming language
◼ Cannot be used as identifiers (variable names)
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 7
Declaring Variables (Part 1)
◼ Before use, variables must be declared
◼ Tells the compiler the type of data to store
Examples: int number_of_bars;
double one_weight, total_weight;
◼ int is an abbreviation for integer.
◼ could store 3, 102, 3211, -456, etc.
◼ number_of_bars is of type integer
◼ double represents numbers with a fractional
component
◼ could store 1.34, 4.0, -345.6, etc.
◼ one_weight and total_weight are both of type double
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Declaring Variables (Part 2)
Two locations for variable declarations
◼ Immediately prior to use ◼ At the beginning
int main() int main()
{ {
… int sum;
int sum; …
sum = score1 + score 2; sum = score1 +
… score2;
return 0; …
} return 0;
}
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 9
Assignment Statements
◼ An assignment statement changes the value of a
variable
◼ total_weight = one_weight * number_of_bars;
◼ total_weight is set to the product one_weight *
number_of_bars
◼ Assignment statements end with a semi-colon
◼ The single variable to be changed is always on the left
of the assignment operator ‘=‘
◼ On the right of the assignment operator can be
◼ Constants -- age = 21;
◼ Variables -- my_cost = your_cost;
◼ Expressions -- circumference = diameter * 3.14159;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 10
Assignment Statements and Algebra
◼ The ‘=‘ operator in C++ is not an equal sign!
◼ The following statement cannot be true in
algebra
◼ number_of_bars = number_of_bars + 3;
◼ In C++, it means the new value of
number_of_bars
is the previous value of number_of_bars plus 3
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 11
Initializing Variables
◼ Declaring a variable does not give it a value
◼ Giving a variable its first value is initializing the variable
◼ Variables are initialized in assignment statements
double mpg; // declare the variable
mpg = 26.3; // initialize the variable
◼ Declaration and initialization can be combined
using two methods
◼ Method 1
double mpg = 26.3, area = 0.0 , volume;
◼ Method 2
double mpg(26.3), area(0.0), volume;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 12
Section 2.1 Conclusion
◼ Can you
◼ Declare and initialize two integers variables to zero?
The variables are named feet and inches.
◼ Declare and initialize two variables, one int and one
double?
Both should be initialized to the appropriate form of 5.
◼ Give good variable names for identifiers to store
◼ the speed of an automobile?
◼ an hourly pay rate?
◼ the highest score on an exam?
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 13
2.2
Input and Output
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Input and Output
◼ A data stream is a sequence of data
◼ Typically in the form of characters or numbers
◼ An input stream is data for the program to use
◼ Typically originates
◼ at the keyboard
◼ at a file
◼ An output stream is the program’s output
◼ Destination is typically
◼ the monitor
◼ a file
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 15
Output using cout
◼ cout is an output stream sending data to the monitor
◼ The insertion operator "<<" inserts data into cout
◼ Example:
cout << number_of_bars << " candy bars\n";
◼ This line sends two items to the monitor
◼ The value of variable number_of_bars
◼ The quoted string of characters " candy bars\n"
◼ Notice the space before the ‘c’ in candy
◼ The ‘\n’ causes a new line to be started following the ‘s’ in bars
◼ A new insertion operator is used for each item of output
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 16
Examples Using cout
◼ This produces the same result as the previous sample
cout << number_of_bars ;
cout << " candy bars\n";
◼ Here arithmetic is performed in the cout statement
cout << "Total cost is $" << (price + tax);
◼ Quoted strings are enclosed in double quotes ("Walter")
◼ Don’t use two single quotes (')
◼ A blank space can also be inserted with
cout << " " ;
if there are no strings in which a space is desired as
in " candy bars\n"
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 17
Include Directives
◼ Include Directives add library files to our programs
◼ To make the definitions of the cin and cout available to
the program:
#include <iostream>
◼ Using Directives include a collection of defined names
◼ To make the names cin and cout available to our program:
using namespace std;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 18
Escape Sequences
◼ Escape sequences tell the compiler to treat characters
in a special way
◼ '\' is the escape character
◼ To create a newline in output use
\n – cout << "\n";
or the newer alternative
cout << endl;
◼ Other escape sequences:
\t -- a tab
\\ -- a backslash character
\" -- a quote character
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 19
Formatting Real Numbers
◼ Real numbers (type double) produce a variety of outputs
double price = 78.5;
cout << "The price is $" << price << endl;
◼ The output could be any of these:
The price is $78.5
The price is $78.500000
The price is $7.850000e01
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 20
Showing Decimal Places
◼ cout includes tools to specify the output of type double
◼ To specify fixed point notation
◼ setf(ios::fixed)
◼ To specify that the decimal point will always be shown
◼ setf(ios::showpoint)
◼ To specify that two decimal places will always be shown
◼ precision(2)
◼ Example: cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The price is "
<< price << endl;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 21
Input Using cin
◼ cin is an input stream bringing data from the keyboard
◼ The extraction operator (>>) extracts data to be used
◼ Example:
cout << "Enter the number of bars in a package\n";
cout << " and the weight in ounces of one bar.\n";
cin >> number_of_bars;
cin >> one_weight;
◼ This code prompts the user to enter data then
reads two data items from cin
◼ The first value read is stored in number_of_bars
◼ The second value read is stored in one_weight
◼ Data is separated by spaces when entered
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 22
Reading Data From cin
◼ Multiple data items are separated by spaces
◼ Data is not read until the enter key is pressed
◼ Allows user to make corrections
◼ Example:
cin >> v1 >> v2 >> v3;
◼ Requires three space separated values
◼ User might type
34 45 12 <enter key>
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 23
Section 2.2 Conclusion
◼ Can you
◼ write an input statement to place a
value in the variable the_number?
◼ Write the output statement to prompt for
the value to store in the_number?
◼ Write an output statement that produces a
newline?
◼ Format output of rational numbers to show
4 decimal places?
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 24
2.3
Data Types and Expressions
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Data Types and Expressions
◼ 2 and 2.0 are not the same number!
◼ A whole number such as 2 is of type int
◼ A real number such as 2.0 is of type double
◼ Numbers of type int are stored as exact values
◼ Numbers of type double may be stored as approximate
values due to limitations on number of significant
digits that can be represented
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 26
Writing Double Constants
◼ Type double can be written in two ways
◼ Simple form must include a decimal point
◼ Examples: 34.1 23.0034 1.0 89.9
◼ Floating Point Notation (Scientific Notation)
◼ Examples: 3.41e1 means 34.1
3.67e17 means
367000000000000000.0
5.89e-6 means 0.00000589
◼ Number left of e does not require a decimal point
◼ Exponent cannot contain a decimal point
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 27
Other Number Types
◼ Various number types have different memory
requirements
◼ More precision requires more bytes of memory
◼ Very large numbers require more bytes of
memory
◼ Very small numbers require more bytes of
memory
Display 2.2
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 28
Type char
◼ Computers process character data too
◼ char
◼ Short for character
◼ Can be any single character from the keyboard
◼ To declare a variable of type char:
char letter;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 29
char constants
◼ Character constants are enclosed in single quotes
char letter = 'a';
◼ Strings of characters, even if only one character
is enclosed in double quotes
◼ "a" is a string of characters containing one character
◼ 'a' is a value of type character
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 30
Reading Character Data
◼ cin skips blanks and line breaks looking for data
◼ The following reads two characters but skips
any space that might be in between
char symbol1, symbol2;
cin >> symbol1 >> symbol2;
◼ User normally separate data items by spaces:
J D
◼ Results are the same if the data is not separated
by spaces:
JD
Display 2.4
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 31
Type Compatibilities
◼ In general, store values in variables of the
same type
◼ This is a type mismatch:
int int_variable;
int_variable = 2.99;
◼ If your compiler allows this, int_variable will
most likely store 2, not 2.99
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 32
int → double (part 2)
◼ Integer values can normally be stored in
variables of type double
double double_variable;
double_variable = 2;
◼ double_variable will contain 2.0
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 33
char → int
◼ The following actions are possible but generally not
recommended!
◼ It is possible to store char values in integer
variables
int value = 'A';
value will contain an integer representing 'A'
◼ It is possible to store int values in char variables:
char letter = 65;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 34
bool → int
◼ The following actions are possible but generally
not recommended!
◼ Values of type bool can be assigned to int variables
◼ True is stored as 1
◼ False is stored as 0
◼ Values of type int can be assigned to bool variables
◼ Any non-zero integer is stored as true
◼ Zero is stored as false
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 35
Arithmetic
◼ Arithmetic is performed with operators
◼ + for addition
◼ - for subtraction
◼ * for multiplication
◼ / for division
◼ Example: storing a product in the variable
total_weight
total_weight = one_weight * number_of_bars;
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 36
Results of Operators
◼ Arithmetic operators can be used with any
numeric type
◼ An operand is a number or variable used by the
operator
◼ Result of an operator depends on the types of
operands
◼ If both operands are int, the result is int
◼ If one or both operands are double, the result
is double
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 37
Division of Doubles
◼ Division with at least one operator of type double
produces the expected results
double divisor, dividend, quotient;
divisor = 3;
dividend = 5;
quotient = dividend / divisor;
◼ quotient = 1.6666…
◼ Result is the same if either dividend or divisor is
of type int
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 38
Division of Integers
◼ Be careful with the division operator!
◼ int / int produces an integer result
(true for variables or numeric constants)
int dividend, divisor, quotient;
dividend = 5;
divisor = 3;
quotient = dividend / divisor;
◼ The value of quotient is 1, not 1.666…
◼ Integer division does not round the result, the
fractional part is discarded!
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 39
Integer Remainders
◼ % operator gives the remainder from integer
division
◼ int dividend, divisor, remainder;
dividend = 5;
divisor = 3;
remainder = dividend % divisor;
The value of remainder is 2
Display 2.6
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 40
Arithmetic Expressions
◼ Use spacing to make expressions readable
◼ Which is easier to read?
Display 2.7
x+y*z or x+y*z
◼ Precedence rules for operators are the same as
used in your algebra classes
◼ Use parentheses to alter the order of operations
x + y * z ( y is multiplied by z first)
(x + y) * z ( x and y are added first)
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 41
Operator Shorthand
◼ Some expressions occur so often that C++
has shorthand operators for them
◼ All arithmetic operators can be used this way
◼ += count = count + 2; becomes
count += 2;
◼ *= bonus = bonus * 2; becomes
bonus *= 2;
◼ /= time = time / rush_factor; becomes
time /= rush_factor;
◼ %= remainder = remainder % (cnt1+ cnt2); becomes
remainder %= (cnt1 + cnt2);
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 42
Display 2.1 (1/2)
Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 43
Display 2.1
(2 /2) Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 44
Display 2.2 Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 45
Display 2.3
Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 46
Display 2.4
Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 47
Display 2.6 Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 48
Display 2.7 Back Next
Copyright © 2018 Pearson Addison-Wesley. All rights reserved.
Slide 2- 49