Operations

!! "
1
Objectives
u To write C++ programs to perform simple calculations
(§2.2).
u To read input from the keyboard using the cin object
(§2.3).
u To simplify programming by omitting the std:: prefix
(§2.4).
u To use identifiers to name variables, constants, functions,
and classes (§2.5).
u To use variables to store data (§§2.62.7).
u To program with assignment statements and assignment
expressions (§2.7).
u To use constants to store permanent data (§2.8).

!! "
2
Objectives (cont.)
u To declare variables using numeric data types (§2.9).
u To use operators to write numeric expressions (§2.9).
u To convert numbers to a different type using casting
(§2.10).
u To represent character using the char type (§2.11).
u To become familiar with C++ documentation, programming
style, and naming conventions (§2.13).
u To distinguish syntax errors, runtime errors, and logic
errors (§2.14).
u To debug logic errors (§2.15).

!! "
3
Example Program
Listing 2.1: Computing the Area of a
Circle
This program computes the area of the
circle.

!! "
4
p p

!! "
5
p p

!! "
6
p p

!! "
7
p p

!! "
8
p p

!! "
9
Reading Input from the Keyboard
#include <iostream>
] int main() {
double radius;
double area;

!! "
10
Omitting the std:: Prefix
u ðou have noticed that std::cout, std::endl,
and std::cin all start with std::.
u std means the standard namespace. C++
divides the world into ³namespaces´ to
resolve potential naming conflicts.
u std::cout means that cout belongs to the
standard namespace.
u To avoid typing ³std::´:
± add the statement: using namespace std;

!! "
11
#include <iostream>
Omitting the std::
using namespace std;
Prefix (cont.)
int main() {
double radius;
double area;

!! "
13
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
std::cout << area;
Y
Y
Y
Y
Y
Y

!! "
15
Assignment Statements
Y
YY
Y
Y

!! "
16
Declaring and Initializing
in One Step
u Y
u

!! "
17
Named Constants
!!"#$%&#
'()*+
Y (,#)

!! "
18
Numerical Data Types
Ú
Y .*/0).12345.*/).12325 30
YY
Y Y Y .3/3**)*5 30
Y Y
Y .)/0.24)345.)/.24)325).0
YY
Y Y Y .)./.++32.+*5 ).0
Y Y
Y
Y .)/0.24)345.)/.24)325).0
YY
Y Y Y .)./.++32.+*5).0
Y Y
6
Y
7 ).0
Y(###2*
0).4.)*#8)40#0*
'YY
7
#0*).4.)*#8)4
Y
7 30
Y(###2*
02+23+))43.)*2#8)40+#0).
'YY
7
+#0).2+23+))43.)*2#8)4
Y
7 40
Y
04#8+).))2#0+).
'YY
7
))2#0+).4#8+).
Y Y6Y
Y9
YY7+

!! "
19
sizeof Function
ðou can use the sizeof function to find the size of a type.
For example, the following statement displays the size of
int, long, and double on your machine.
cout << sizeof(int) << " " << sizeof(long) << " " <<
sizeof(double);

!! "
20
Synonymous Types
u short int is same as short.
u unsigned short int is same as unsigned short.
u unsigned int is same as unsigned.
u long int is same as long.
u unsigned long int is same as unsigned long.
u E.g.,
short int i = 2;
is same as
short i = 2;

!! "
21
Numeric Literals
int i = 34;
long k = 1000000;
double d = 5.0;

!! "
22
What Are £ l
u The float and double types are used to represent
numbers with a decimal point.
u Why are they called floatingpoint numbersl
u These numbers are stored in scientific notation.
u When a number such as 50.534e+1 is converted
into scientific notation such as 5.0534, its
decimal point is moved (i.e., floated) to a new
position.

!! "
23
Numeric Operators
Ú
O O
!"!

!! "
24
Integer Division
+, , *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

!! "
25
Remainder Operator
3%2=1
8%2=0
33 % 2 = 1
þ

!! "
27
Overflow
When a variable is assigned a value that is
too large to be stored, it causes
£ . For
example, executing the following statement
causes
£ , because the largest value
that can be stored in a variable of the short
type is 32767. 32768 is too large.

!! "
29
Arithmetic Expressions
3' 4 10( Ä 5)( ' ' ) 9' 4
' 9( ' )
5 Ä
is translated to

!! "
30
ðour Turn: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
Ô ( 95 )( £
32)
ù u

!! "
31
Shorthand Assignment Operators
4
Ô
8 Y84 YY84
0 604 660 4
: Y:4 YY:4
Y4 YY4
; Y;4 YY;4

!! "
32
Increment and
Decrement Operators
Operator Name Description
OOvar preincrement The expression increments by 1 and
evaluates to the
value in var £
the increment.
varOO postincrement The expression (var++) evaluates to the
value in var and increments var
by 1.
var predecrement The expression (var) decrements var by
1 and evaluates to the
value in var
£
the decrement.
var postdecrement The expression (var) evaluates to the
value in var and decrements var
by 1.

!! "
33
Increment and
Decrement Operators, cont.
Y Y üa e effect as
Y
Y Î Y
Y
YY

!! "
34
Increment and
Decrement Operators, cont.
Y
< Y : ) 8
Y : ) 8 < .

!! "
36
Conversion Rules
When performing a binary operation involving two operands of different
types, Java automatically converts the operand based on the following rules:
# YY
Y
Y Y
Y>
?Y @/)5
/
=Y 5
Y Y/Y 5)+
/A
Y
Y
5

!! "
38
NOTE
Casting does not change the variable being cast.
For example, d is not changed after casting in the
following code:
double d = 4.5;
int i = static_cast<int>(d); // d is not changed

!! "
39
Example: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.
ü

!! "
40
Character Data Type
char letter = 'A'; //(ASCII)
char numChar = '4'; //(ASCII)

!! "
42
Escape Sequences for Special Characters
u
uu
±
±
±
±
±
±±
± !
"
±#$ "
%

!! "
43
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

!! "
44
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

!! "
45
Casting between char and
Numeric Types
Y Y
9
Y Y/Y 5
+2
9
/
5+2

!! "
46
Numeric Operators on Characters
The char type is treated as if it is an integer of the byte size. All numeric operators
can be applied to char operands. A char operand is automatically cast into a number
if the other operand is a number or a character. For example, the following
statements
Display
i is 101
j is 99
99 is the ASCII code for character c

!! "
47
Note
u The ASCII number for lowercase letters are
consecutive integers starting from the code for 'a',
then for 'b', 'c', ..., and 'z'.
u The same is true for the uppercase letters.
Furthermore, the ASCII code for 'a' is greater than
the code for 'A'. So 'a'  'A' is the same as 'b'  'B'.
u For a lowercase letter ch, its corresponding
uppercase letter is
static_cast<char>('A' + (ch  'a')).

!! "
48
Example:
Computing Loan Payments
This program lets the user enter the interest
rate, number of years, and loan amount and
computes monthly payment and total
payment.
1 1
Ô
£
pr12
(1 Ä
p
)
u

!! "
49
Example: Monetary Units
u u

!! "
50
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; remainingAmount
remainingAmount = remainingAmount % 100;
initialized
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;

!! "
51
p p
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

!! "
52
p p
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

!! "
53
p p
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

!! "
54
p p
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;

!! "
55
Example: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
/* ctime example */
#include <iostream>
#include <time.h>
using namespace std;
int main ()
{
time_t rawtime;
time ( &rawtime );
cout << "The current local time is:"<< ctime (&rawtime);
return 0;
}

!! "
56
Programming Style and
Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles

!! "
57
Much more than documents.
Discover everything Scribd has to offer, including books and audiobooks from major publishers.
Cancel anytime.