Sie sind auf Seite 1von 35

Lesson 2: Built-in Data Types

Slide 1: Lesson Outline


This document is designed to help you take notes while watching the videos for this
lesson. Print these slides before going to the Video Lectures.
Note: Reviewing this material is not sufficient to fully understand the topic; you should
also complete the readings and exercises.
Review these slides

Integer Data Type (slides 2-10)

Identifier and Variable Names (slides 11-24)

Character Data Type (slides 25-38)

Floating-Point Data Types (slides 39-55)

Arithmetic Operators (slides 57-58)

Implicit Type Conversion (slides 59-61)

Explicit Type Conversion (slides 62-64)

Arithmetic Assignment (slides 65-67)

String Data Type (slides 68-78)

Lesson 2

Slide 2: Integer Data Type


Object

Components in problem solving are called objects.

Objects made up of:


Attributes: describe what it is
Actions: describe what it can do

Example 1:

Pencil object. What are its attributes?


Example 2:

Car object. What are its attributes and actions?

Slide 3: Integer Data Type


Integer Object - Declaration
There are several kinds of integer objects.
The most commonly used integer object is int, which ranges from -2,147,483,648 to
2,147,483,647.
Declaration statement
Example:
int k;
int classSize;
can also be written as:
int k, classSize;
What are the values of the variables k and classSize ?

Lesson 2

Slide 4: Integer Data Type


Integer Object-Assignment
Three ways to assign a value to a variable:
1. Assignment Statement
Assigns a value to a variable. Syntax: variable = expression;
k = 65;
classSize = 50;
2. Initialized Declaration
Combines declaration and assignment.
int k = 65;
int classSize = 50;
3. Ask User to Provide Value
cout << "Enter class size: ";
cin >> classSize;

Slide 5: Integer Data Type


Integer Object
Sometimes want an integer object that will not change values during execution of
program.
const int WEEK_DAYS = 7;
const int WKS_IN_YR = 52;

Integer Operations:
int a = 1, b = 2, c = 3;
-

addition:
subtraction:
multiplication:
negation:

Lesson 2

a + 4 value is 1 + 4 = 5
c - 1 value is 3 - 1 = 2
b * c value is 2 * 3 = 6
- a value is -1

Slide 6: Integer Data Type


Integer Operations:
int a = 17, b = 3;
- integer division: a / b value is 17/3 = 5
- remainder: a % b value is 17 % 3 = 2
Example of Uses:
1) Convert 100 inches into feet and inches.
100/12 = 8
100 % 12 = 4
So, 100 inches is equivalent to 8 feet, 4 inches.
2) How do you know if a number is odd or even?
Check video for answers.

Slide 7: Integer Data Type


Assignment Operator ( = )
Syntax object = expression;
The value of the expression is assigned to the object.
Original value is destroyed.
Example:
int a=1, b=2;
a = 12; (constant object)
a = b; (integer object)
a = b + 1;

Lesson 2

Slide 8: Integer Data Type


Assignment Operator ( = ) (cont'd)
Example:
a = a + 1; (counter)
a = b = 100; (multiple assignment)
Not valid! Why? a + 1 = b + 4;

Slide 9: Integer Data Type


Input and Output
Can use cout to display the value of integer expressions and cin to assign a value to
an integer variable.
Example:
cout << " What is the size? ";
cin >> size;
cout << "Size is: " << size;

Lesson 2

Slide 10: Integer Data Type


Program Which Uses Integers
int main()
{
int quarters, dimes, nickels, pennies;
cout << "Enter number of quarters: ";
cin >> quarters;
cout << "Enter number of dimes: ";
cin >> dimes;
cout << "Enter number of nickels: ";
cin >> nickels;
cout << "Enter number of pennies: ";
cin >> pennies;
int total = 25 * quarters + 10 * dimes + 5 * nickels +
pennies;
cout << "The total amount is"<< (total/100)<<"dollars and "
<< (total % 100) << "cents." << endl;
return 0;
}

Slide 11: Identifiers and Variable Names

Identifiers used to name constants, variables and various other things as well;

Have seen to date:quarters, dimes, nickels, pennies, total, size, etc.;

Three factors affect the choice of names:


1. Rules of C++
2. Conventions adopted by C++ programmers
3. Good style

Lesson 2

Slide 12: Identifiers and Variable Names


Rules

An identifier may contain:


- upper case letters (A, B, , Z)
- lower case letters (a,b,c,,z)
- digits (0,1,2,,9)
- underscore ( _ )

Identifier must begin with a letter.


(can start with _ but not good style)

Case sensitive:
QUARTER, Quarter, quarter
are three different names

Slide 13: Identifiers and Variable Names


Conventions

Use lower case names for variables.


Ex: quarters, pennies, size

If variable name consists of more than one word, start each new word with an upper
case lette.r
Ex: muffinPrice, studentId

An alternate method for multi-word names is to separate each word with an


underscore.
Ex: muffin_price, student_id

Use upper case letters for constant identifiers


Ex: const int MAX_LENGTH = 80;

Lesson 2

Slide 14: Identifiers and Variable Names


Good Style
What does the following program do?
const double BTR_1 = 0.15;
const double STR_2 = 0.10;
const double LXVRW = 40000.0;
void main()
{
cout <<" ?";
double stuff;
cin >> stuff;
double theAnswer;
if (stuff < LXVRW)
theAnswer = stuff * BTR_1;
else
theAnswer =stuff * (BTR_1 + STR_2);
cout<< "Answer = " << theAnswer << endl;
}
Check video for answers.

Slide 15: Identifiers and Variable Names


Good Style (cont'd)
const double BASE_TAX_RATE = 0.15;
const double SUPER_TAX_RATE = 0.10;
const double SUPER_LEVEL= 40000.0;
void main()
{
cout <<" Enter income: ";
double income;
cin >> income;
double tax;
if (income < SUPER_LEVEL)
tax = income * BASE_TAX_RATE;
else
tax =income * (BASE_TAX_RATE + SUPER_TAX_RATE);
cout<< "Tax = " << tax << endl;
}
Lesson 2

Slide 16: Identifiers and Variable Names


Good Style (cont'd)

Sometimes you will see:

int count; // Number of coffees

Better style to do:

int numCoffees; // Number of coffees

Slide 17: Output Statements

The cout statement produces output on the screen;

Items in double quotes (") are treated as a message and shown exactly as they
appear;

Items not in double quotes must therefore be variables or expressions;

Each item is separated by the output operator <<;

Need to include library iostream as cout is predefined there.

Slide 18: Output Statements (cont'd)


What will the output of the following statements be?
1) x = 8; y = 6;
cout << x << y;
cout << " " << y;
Check video for answers.

Lesson 2

Slide 19: Output Statements (cont'd)


What will the output of the following statements be?
1) x = 8; y = 6;
cout << x << y;
cout << " " << y;
Conclusion:
Separate cout statements do not necessarily produce separate lines of output.
To begin a new line of output, use the endl manipulator. Causes printing cursor to go to
the beginning of the next line.

Slide 20: Output Statements (cont'd)


What will the output of each of these program fragments be?
2) yards = 8;
feet = 3 * yards;
cout << yards << " yd. is";
cout << feet << " ft.";
3) yards = 8;
feet = 3 * yards;
cout << yards << " yd. is";
cout << endl;
cout << feet << " ft.";

Slide 21: Output Statements (cont'd)


What will the output of each of these program fragments be?
4) cout << "Yes";
cout << endl << "No.";
5) cout << "Yes" << endl;
cout << endl;
cout << "No";
6) cout << "Yes";
cout << "No";
Lesson 2

10

Slide 22: Basic Types of Integers


Type Name

Memory Size

short
(short int)
int
long
(long int)

2 bytes

4 bytes
4 bytes

Size Range
-32,768 to 32,767
-2,147,483,648 to
2,147,483,647
-2,147,483,648 to
2,147,483,647

Slide 23: cin - Some Facts

cin waits for input from the keyboard;

Sets the first variable equal to the first value entered in the keyboard, the second
variable equal to the second value entered, and so forth;

Program reads input only once user has pressed the <return> key;

Numbers in input must be separated by one or more spaces or by a line break;

Will skip over any number of line breaks or blanks until it finds the next input value.

Lesson 2

11

Slide 24:
2 cin - Some
S
Fac
cts (cont'd)
Possible formatss of input:
1) 10
0 11 12
Example
e:
int a, b, c;
cin >> a >> b >> c;
= <en
nter> key
= spacce

2) 10
0

11

12

3) 10
0 11
12
4) 10
0 11
12
0
5) 10
11
12

Slide 25:
2 Chara
acter Data Type
Charac
cter Obje
ects

A varriable of typ
pe char can
n store any single charracter value
e;

Chara
acter data in a C++ prrogram is re
epresented
d by writing the approp
priate symb
bol
betwe
een single quote
q
signss;
Exam
mple:
'a ' '#
#' 'Z ';

Decla
aring and in
nitializing a variable of type charaacter.
char letter = 'a';;

Lesson 2

12
2

26: Chara
acter Data Type
cter Obje
ects (contt'd)
e:
ade;
< "Enter
r your gr
rade: ";
> grade;
< "You received
r
< endl;
a grade of " << grade <<

espace cha
aracters = characterss that produ
uce empty (white) spa
ace when
such as bla
anks, new line characte
er and horizontal tabss.

27: Chara
acter Data Type
cter Obje
ects (contt'd)
that i, j are
e int variables and ch is a char vaariable.
ill the conte
ents of i , j and ch be after
a
input??
ent

Data
a

> i;

32

> i >> j;

4 60
6

or answer
rs.
video fo

13
3

28: Chara
acter Data Type
cter Obje
ects (contt'd)
> i >> ch;

25

> i >> ch;

25
A

> i >> ch;

25A
A

> i >> j >>


> ch; 1 2 8
> i >> ch;

46 32

14
4

Slide 29: Character Data Type


Escape Character

If you want the single quote ( ' ), character need to express it as \'

Example:
const char QUOTE = '\'';
\ (known as the backslash character) acts as an escape character in C++

More common uses of the escape character:

In program

Effect

\'

'

\\

\n

new line

\t

tab character

\a

bell character

Slide 30: Character Data Type


Escape Character (cont'd)
Example 1:
If you wanted to output
She replied, "You can quote me."
What is the corresponding cout command?
Check video for answers.
Lesson 2

15

Slide 31: Character Data Type


Escape Character (cont'd)
Example 2:
If you wanted to output
Read the file c:\windows\readme.txt
What is the corresponding cout command?

Slide 32: Character Data Type


Escape Character (cont'd)
What will the following code fragment output be?
cout << " This code\nuses the\n " ;
cout << " quot; newline character\n ";
cout << " and makes the speaker beep\a. " ;

To begin a new line, use \n , when it can be made the last character of a string.

To begin a new line, use endl if the last output of a line is a value.

Slide 33: Character Data Type


Input whitespace Characters

There are times when you do not want to skip over whitespace.

cin.get() (instead of cin >>..) reads the next input character regardless of whether
the next character is whitespace or not.
Example:
char nextCh;
cin.get(nextCh); // will read any character

Lesson 2

16

Slide 34:
3 Chara
acter Data Type
Input whitespa
ace Chara
acters (co
ont'd)
e:
Example
What is the input in
n each case
e?
char ch1
1, ch2, ch3;;

Check video fo
or answer
rs.

Slide 35:
3 Last Look
L
at Output
O
wiith int Ty
ype

cout can
c be used
d to outputt variables of
o type chaar , int and d
double;

cout with
w char outputs
o
justt that chara
acter;

cout with
w int displays just value
v
of inte
eger, using
g least amou
unt of spacce;

Can add
a whitesp
pace to output by writing setw(n)
n) (which is read "set w
width to n"));
NOTE
E: It only afffects the next item!

3 Last Look
L
at Output
O
wiith int Ty
ype (contt'd)
Slide 36:
Example
e:
int first=
=1, last = 9999;
9
cout <<
< setw( 6 ) << first <<
< last ;
Output:
(where

Lesson 2

19999
1
stands for a blank)

17
7

37: Last Look


L
at Output
O
wiith int Ty
ype (contt'd)
uld I generrate the folllowing outp
put using a single coutt statementt?
of quarterss =
of dimes =
of nickels =
of penniess =

45 (qua
uarters)
107 (dim
mes)
3 (nic
ickels)
24 (pen
ennies)

video fo
or answer
r.

38: Last Look


L
at Output
O
wiith int Ty
ype (contt'd)
e able to usse setw nee
ed to include the file io
omanip.
directive #include
#
<io
iomanip> att the beginning of you
ur program..
programs should
s
begiin with:
clude <io
ostream> // for cout,cin
c
clude < iomanip
i
> // for setw
ng namesp
pace std;

39: Floatiing-Pointt Data Ty


ypes
Numbers
numbers arre numberss with a who
ole and fracctional partt.
s of real nu
umbers are float, doub
ble, long doouble.
rence betwe
een them iss the level of
o accuracyy. Double has a higherr accuracy a

18
8

Slide 40: Floating-Point Data Types


Real Numbers (cont'd)
Two ways of representing real numbers.
1) Fixed point = whole part and fraction part
Example:
Number
-12.352
123.4

Whole
-12
123

Fraction
.352
.4

Slide 41: Floating-Point Data Types


Real Numbers (cont'd)
2) Floating point = scientific notation
<mantissa> . <exponent>
Example 1:
Number Mantissa Exponent
-5.07e15 -5.07 15
means -5.07 x 10 15 =
-5070000000000000 (13 zeroes)

Lesson 2

19

Slide 42: Floating-Point Data Types


Real Numbers (cont'd)
2) Floating point = scientific notation
<mantissa> . <exponent>
Example 2:
Number Mantissa Exponent
1.23e-5 1.23 5
means 1.23 x 10 = 0.0000123

Real number operations, standard +, -, *, / and negation.

Cannot use the % operator with real numbers.

Slide 43: Floating-Point Data Types


Real Numbers (cont'd)
To declare and initialize a variable of type float or double:
float y, z;
double a = 12.3;
float x = 0.1, w, s;
const double PI = 3.14159;

Lesson 2

20

Slide 44: Floating-Point Data Types


Real Numbers (cont'd)
What output do you think is generated by the following?
void main()
{
cout << 4.5 << endl;
cout << -.375 << endl;
cout << 10.6666666 << endl;
cout << 67800000.0 << endl;
cout << 523.0 << endl;
cout << 523000000000. <<
endl;
cout << 0.000098 << endl;
}

4.5
-0.375
10.6667
6.78e+007
523
5.23e+011
9.8e-005

Check video for explanations, as the answers are on the slide.

Slide 45: Floating-Point Data Types


Output Format for Real Numbers
There are three modes for output of real values:

Default : depending on size of number, default chooses between scientific and


fixed.

Scientific: for very small or very large numbers.

Fixed: the way we are used to seeing real numbers.

When formatting output of real numbers, you need to consider the total number of
positions and the number of decimal places.

Lesson 2

21

Slide 46: Floating-Point Data Types


Manipulators

Manipulators are used only in input and output statements.

endl *, fixed, showpoint, setw *, and setprecision are manipulators that can be used
to control output format.

endl is use to terminate the current output line and create blank lines in output.

* Have already seen with int type.

Slide 47: Floating-Point Data Types


Manipulators (cont'd)
Use the following statement to specify that (for output sent to the cout stream) decimal
format (not scientific notation) be used, and that a decimal point be included (even for
floating values with 0 as fractional part)
cout << fixed << showpoint ;

Slide 48: Floating-Point Data Types


Manipulators (cont'd)
Setprecision(n)

Requires #include <iomanip> and appears in an expression using insertion operator


(<<).

If fixed has already been specified, argument n determines the number of places
displayed after the decimal point for floating point values.

Remains in effect until explicitly changed by another call to setprecision.

Lesson 2

22

Slide 49: Floating-Point Data Types


Output Format for Real Numbers
Example 1:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed << showpoint;
cout << setw(8) << setprecision(3) << a << endl;

cout << setw(7) << setprecision(2) << a << endl;

Check video for answer.

Slide 50: Floating-Point Data Types


Output Format for Real Numbers (cont'd)
Example 1:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed << showpoint;

cout << setw(2) << setprecision(1) << a << endl;

Slide 51: Floating-Point Data Types


Output Format for Real Numbers (cont'd)
Example 1:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed << showpoint;
cout << setw(2) << setprecision(2) << a << endl;

cout << setw(5) << setprecision(0) << a << endl;

Lesson 2

23

Slide 52: Floating-Point Data Types


Output Format for Real Numbers (cont'd)
Example 2:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed; // showpoint removed
cout << setw(8) << setprecision(3) << a << endl;

Slide 53: Floating-Point Data Types


Output Format for Real Numbers (cont'd)
Example 2:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed; // showpoint removed
cout << setw(7) << setprecision(2) << a << endl;
cout << setw(2) << setprecision(1) << a << endl;

Slide 54: Floating-Point Data Types


Output Format for Real Numbers (cont'd)
Example 2:
What output is generated by the following program segment?
double a = 123.545;
cout << fixed; // showpoint removed
cout << setw(2) << setprecision(2) << a << endl;

cout << setw(5) << setprecision(0) << a << endl;

Lesson 2

24

Slide 55:
5 Floatiing-Pointt Data Ty
ypes
Outputt Format for Real Numbers (cont'd
d)
Example
e 3:
What ou
utput is gen
nerated by the
t followin
ng program
m segment?
double a = 123.545;
//cout << fixe
ed << sho
owpoint;
cout << setw(8) << set
tprecisio
on(3) << a << end
dl;

Slide 56:
5 Floatiing-Pointt Data Ty
ypes
Manipu
ulators/H
Header Files

Lesson 2

25
5

Slide 57:
5 Arithm
metic Operators
Operattors

+, -, *, /, % are
e called ope
erators.

C++ uses conve


entions of algebra.
a

Orderr of evaluattion is contrrolled by prrecedence.

Prece
edence for the
t operato
ors we have
e seen to daate:
1. ( )
2. Un
nary + or 3. * / % from le
eft to right
4. + - from left to
t right
5. <<
< >> stream
m insertion//extraction
6. = single
s
assig
gnment stattement

Slide 58:
5 Arithm
metic Operators
Operattors (con
nt'd)

Some
e examples::
1) 2 + 3 * 5 - 5 * 2 / 5 + 10
1 (25)
2) (2 + 3) * 5 - 5 * (2 / 5) + 10 (35)
5)
3) (2 + 3) * 5 - (5 * (2 / 5)) + 10) (15

Write
e as a C++ statement:

Lesson 2

26
6

Slide 59: Implicit and Explicit Type Conversion


Implicit
Convert less complex type to more complex when applying operator.

integer operator short ==> integer

integer operator real ==> real

char operator integer ==> integer

Example 1:
What will be stored in r ?
double r;
int a = 4, b = 2;
r = a/b;
Check video for answers.

Slide 60: Implicit and Explicit Type Conversion


Implicit (cont'd)
Example 2:
What will be stored in r ?
double r = 2.0, s;
int a = 5, b = 2, c;
c = a/b;
s = a/b;
s = a/r;
c = a/r; //warning

Lesson 2

27

Slide 61: Implicit and Explicit Type Conversion


Implicit (cont'd)
Example 3:
What will be stored in r ?
char c = 'a'; //ascii code = 97
int a = 16;
double d = 1.5;
cout << (c + a + d) << endl;
// Result will be 114.5. How?

Slide 62: Implicit and Explicit Type Conversion


Explicit
Involves attaching the type to the object.

char(70) converts int 70 to char 'F'

double(5) converts int 5 to double 5.0

int(1.75) converts double 1.75 to int 1

Slide 63: Implicit and Explicit Type Conversion


Explicit (cont'd)
Example 1:
Value in each variable?
int a = 11, b;
double d = 1.23, f;
b = a / 5;
f = a / 5;
// How do I store 2.2 in f?
// What is stored in f & b?
f = d * a;
b = d * a;
Check video for answer.
Lesson 2

28

Slide 64: Implicit and Explicit Type Conversion


Explicit (cont'd)
Exercise:
Each statement uses type conversion. Give the value assigned to x.
a) int x ;
x = int(3.8);
b) int x, y =20;
x = int(3.8 * y );
c) char x ;
x = char(65); //'A'
d) int x, y =20;
x = int(3.8) * y ;
f) char ch ='F'; //70
int x ;
x = ch ;

Slide 65: Arithmetic Assignment


Each of the numerical operators +, -, *, / and % can be combined with the assignment
operator to create an arithmetic assignment operator.

total_tax += state_tax; is equivalent to


total_tax = total_tax + state_tax;

count = count - 1; can be written as


count -= 1;

twice = twice * 2; can be written as


twice *= 2;

Lesson 2

29

Slide 66: Arithmetic Assignment (cont'd)


Valid or invalid? Explain
salary =+bonus;
salary + = bonus;

Slide 67: Arithmetic Assignment (cont'd)


Fill in the values for the objects a and b.
#include <iostream>
using namespace std;
void main()
{
int a = 20, b;
a -= 4; // a = ______
a
b
a
b
a
}

= 20;
= 4;
+= b; // a = ______
*= a; // b = ______
%= b + 6; // a = ______

Check video for answers.

Lesson 2

30

Slide 68: String Data Types

We have already seen strings in output statements:


cout<< "Hello world;

To be able to declare an object of type string we need to add:


#include <string>

Declaring a string:
string fName, lName;

Declaring and initializing a string:


string message= "Hello";

Slide 69: String Data Types


Example 1
Input/output of strings:

Can use cin, cout with the << and >> operators.

For input, whitespace is used to separate the objects.

Example 1:
cin >> fName >>
cout << fName <<
cout << setw(10)
<< setw(10)

lName;
lName << endl;
<< fName
<< lName << endl;

Check video for answer.

Lesson 2

31

70: String
g Data Ty
ypes
ple 2
ude <iost
tream> //
/ for cin
n, cout
ude <ioma
anip> // for setw
w()
ude <stri
ing> // for
f
strin
ng
namespac
ce std;
ain()
Declarati
ion of va
ariables
ng teamN
Name, coa
ach;
teamID; // leagu
ue assign
ns teamID
D #
r level; // teams
s play at
t level A
A, B, C
Request input
i
fro
om user
<< "Ent
ter team name, id
d, level and coac
ch: " << endl;
>> teamN
Name >> teamID
t
>>
> level >
>> coach;
;

32
2

71: String
g Data Ty
ypes
ple 2 (con
nt'd)
<
<
<
<

"Team: "
setw(10)
setw(10)
setw(10)
n 0;

<<
<<
<<
<<

te
eamName <<
< endl;
te
eamID << " (ID)" << endl
le
evel << " (Level) " << end
dl
co
oach << " (Coach) " << end
dl;

am name, id, level and


eam 218 A Acemian
A
COMPTeam
)
)
n (Coach)
ny key to co
ontinue.

72: String
g Data Ty
ypes
tions
Concatena
ation:
pending of one
o string onto
o
the en
nd of anotheer.
e:
g word1 = "Hello", word2 = "World
d", mess;
;
= word1 + word2;

33
3

Slide 73: String Data Types


Operations (cont'd)
Remember:
word1= "Hello"
word2 = "World"
mess = "HelloWorld"
Example:
mess = word1 + "_" + word2;
word1 += word2;
word1 += "!!!";

Slide 74: String Data Types


Operations (cont'd)
String Length:
Function length() returns an unsigned integer value that equals the number of
characters currently in the string.
Example:
string word1 = "Hello!!!";
cout << word1.length(); // output ????

Slide 75: String Data Types


find() Function

Function find() returns an unsigned integer value that is the beginning position for
the first occurrence of a particular substring within the string.

The substring argument can be a string constant, a string expression or a char value.

If the substring was not found, function find returns the special value string::npos.

Lesson 2

34

Slide 76: String Data Types


substr() Function

Function substr() returns a particular substring of a string.

The first argument is an unsigned integer that specifies a starting position within the
string.

The second argument is an unsigned integer that specifies the length of the desired
substring.

Positions of characters within a string are numbered starting from 0, not from 1.

Slide 77: String Data Types


What is Exact Output?
#include <iostream>
#include <string> // for functions length(),
// find(), substr()
using namespace std;
int main ( )
{
string stateName = " Mississippi " ;
cout << stateName.length( ) << endl;
cout << stateName.find( " is " ) << endl;

Slide 78: String Data Types


What is Exact Output? (cont'd)
// stateName = "Mississippi";
cout << stateName.substr( 0, 4 ) << endl;
cout << stateName.substr( 4, 2 ) << endl;
cout << stateName.substr( 9, 5 ) << endl;
return 0 ;
}

Lesson 2

35