You are on page 1of 57

Chapter 2 Primitive Data Types and

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.6-2.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

Trace a Program Execution


#include <iostream> allocate memory
for radius
int main() {
radius no value
double radius;
double area;

// Step 1: Assign radius


radius = 20;

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

 !! "
5
p p

Trace a Program Execution


#include <iostream> memory

int main() { radius no value


double radius; area no value
double area;

// Step 1: Assign radius allocate memory


radius = 20; for area

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

 !! "
6
p p

Trace a Program Execution


assign 20 to radius
#include <iostream>

int main() { radius 20


double radius;
double area; area no value

// Step 1: Assign radius


radius = 20;

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

 !! "
7
p p

Trace a Program Execution


#include <iostream> memory

int main() { radius 20


double radius;
double area;
area 1256.636

// Step 1: Assign radius


radius = 20; compute area and assign it
to variable area
// Step 2: Compute area
area = radius * radius * 3.14159;

// Step 3: Display the area


std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

 !! "
8
p p

Trace a Program Execution


#include <iostream>
memory
int main() { radius 20
double radius;
double area; area 1256.636

// Step 1: Assign in radius


radius = 20;
print a message to the
// Step 2: Compute area console
area = radius * radius * 3.14159;

// Step 3: Display the area


std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

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

// Step 1: Input radius


std::cout << ³Please enter radius.´ << std::endl;
std::>> radius;

// Step 2: Compute area


area = radius * radius * 3.14159;

u// Step 3: Display the area




std::cout << "The area is ";
std::cout << area << std::endl;
}

| 
       
   

 !! "
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;

// Step 1: Input radius


cout << ³Please enter radius.´ << endl;
cin >> radius;

// Step 2: Compute area


area = radius * radius * 3.14159;

// Step 3: Display the area


cout << "The area is ";
cout << area << endl;
}
| 
       
   

 !! "
12
Identifiers
u An identifier is a sequence of characters that
consists of letters, digits, and underscores (_).
u An identifier must start with a letter or an
underscore. It cannot start with a digit.
u An identifier cannot be a reserved word. (See
Appendix A, ³C++ Keywords,´ for a list of
reserved words.)
u An identifier can be of any length, but your C++
compiler may impose some restriction. Use
identifiers of 31 characters or fewer to ensure
portability.

| 
       
   

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

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
std::cout << area;
| 
       
   

 !! "
14
Declaring Variables
Y 
  

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)4 0#0*
 ' YY
7
 #0* ).4.)*#8)4
„   
Y
7 30 Y(###2*
 02+23+))43.)*2#8)4 0+#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

˜ ë ë is a constant value that appears directly


in a program. For example, 34, 1000000, and 5.0
are literals in the following statements:

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 floating-point 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

5 % 2 yields 1 (the remainder of the division)

| 
       
   

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

Suppose today is Saturday and you and your


friends are going to meet in 10 days. What day is it
in 10 daysl ðou can find that day is Tuesday using
the following expression:
 #  $! %$ #   &!!'
 &!!' $ ( #
+% O ,  (  
*$!  #   &!!'  * !#
)!  #
| 
       
   

 !! "
26
ðour Turn: Displaying Time
Write a program that obtains hours and
minutes from seconds.

þ    


| 
       
   

 !! "
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.

short value = 32767 + 1;


| 
       
   

 !! "
28
Underflow
When a variable is assigned a value that is too
small to be stored, it causes Ô
£  . For
example, executing the following statement causes
Ô
£  , because the smallest value that can be
stored in a variable of the short type is -32768. -
32769 is too small.

short value = -32769;

| 
       
   

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

is translated to

(3+4*x)/5 ± 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

| 
       
   

 !! "
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 


Y Y üamee ect as


Y  
  OO   -  O .
 !&/ " -   .

| 
       
   

 !! "
34
Increment and
Decrement Operators, cont.

Using increment and decrement operators


makes expressions short, but it also makes
them complex and difficult to read. Avoid
using these operators in expressions that
modify multiple variables, or the same
variable for multiple times such as this:
int k = ++i + i.
| 
       
   

 !! "
35
Numeric Type Conversion
Consider the following statements:

  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:

1. If one of the operands is long double, the other is converted into


long double.
2. Otherwise, if one of the operands is double, the other is
converted into double.
3. Otherwise, if one of the operands is float, the other is converted
into float.
4. Otherwise, if one of the operands is unsigned long, the other is
converted into unsigned long.
5. Otherwise, if one of the operands is long, the other is converted
into long.
6. Otherwise, if one of the operands is unsigned int, the other is
converted into unsigned int.
7. Otherwise, both operands are converted into int.
| 
       
   

 !! "
37
Type Casting
(9 YY 
Y 
     ) / =Y Y 5

# 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)

NOTE: The increment and decrement operators can


also be used on char variables to get the next or
preceding character. For example, the following
statements display character b.
char ch = 'a';
cout << ++ch;
| 
       
   

 !! "
41
Read Characters
ho read a character from the keyboard, use

cout << "Enter a character: ";


char ch;
cin >> ch;

| 
       
   

 !! "
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

int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51


cout << "i is " << i << endl; // i is decimal 101
int j = 2 + 'a'; // (int)'a' is 97
cout << "j is " << j << endl;
cout << j << " is the ASCII code for character " <<
static_cast<char>(j) << endl;

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.

pÔ r  Ä



p

1 1
Ô
£
p r12
(1  Ä

p
)
u  

| 
       
   

 !! "
49
Example: Monetary Units

This program lets the user enter the amount in


decimal representing dollars and cents and output
a report listing the monetary equivalent in single
dollars, quarters, dimes, nickels, and pennies.
ðour program should report maximum number of
dollars, then the maximum number of quarters,
and so on, in this order.

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;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;

| 
       
   

 !! "
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;

// Find the number of quarters in the remaining amount numberOfOneDollars


int numberOfQuarters = remainingAmount / 25; assigned
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;

| 
       
   

 !! "
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;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25; remainingAmount
remainingAmount = remainingAmount % 25; updated

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;

| 
       
   

 !! "
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;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25; numberOfOneQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount numberOfOneQuarters


int numberOfDimes = remainingAmount / 10; assigned
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;

| 
       
   

 !! "
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;

// Find the number of quarters in the remaining amount


int numberOfQuarters = remainingAmount / 25; numberOfQuarters 2
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining amount


int numberOfDimes = remainingAmount / 10; remainingAmount
remainingAmount = remainingAmount % 10; updated

// Find the number of nickels in the remaining amount


int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining amount


int numberOfPennies = remainingAmount;

| 
       
   

 !! "
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