Data Types-C++
Data Types-C++
Over view
Bits/Memory
Data Types
Type Conversion
Operators
Control Structures
Arrays
2
A Data Type
A data type is
A set of values AND
A set of operations on those values
10
11
BIT
Binary Digit
pattern or a sequence of 0s and
1s.
12
13
Data Type:
A set of values together with a set of operations is
called a data type.
C++ data types fall into three categories
Simple Data Type.
Structured Data Type.
Address(Pointers).
15
16
Major Classification
User Defined data type
Programmer-created data type
Set of acceptable values and operations defined by a
programmer using C++ code
User-defined Type
Built-in Type
Derived Type
structure
union
class
enumeration
array
function
pointer
reference
Integral Type
int
Void
char
Floating Type
float
double
18
simple
integral
char short
structured
enum floating
array struct
class
union
address
long double
pointer
reference
19
Primitive types
integral
char
short
floating
int
long
bool
float
unsigned
20
Size Unique
representable values
8-bit
256
16-bit
65 536
32-bit
= 28
= 216
= 232 (~4 billion)
551 616
= 264 (~18
21
Memory (ByteS)
Minimum Value
Maximum Value
Bool
Char
-128
127
Unsigned Char
255
Short
-32768
32767
Unsigned Short
65535
int
-32768
32767
unsigned int
65535
Long
-2147483648
2147483647
unsigned long
4294967295
float
double
4
8
10-38
10-308
1038
10308
long double
10
10-4932
104932
22
24
Integer
An integer type is a number without a
fractional part. It is also known as an
integral number. C++ supports three different
sizes of the integer data type: short int, int
and long int.
sizeof(short int)<= sizeof(int)<= sizeof(long int)
Short int
int
long int
25
26
Storing Integers
Integers are whole numbers (numbers without a
fractional part).
For example, 134 and 125 are integers,
28
Unsigned Representation
29
Example
Store 7 in an 8-bit memory location using
unsigned representation.
Solution
First change the integer to binary, (111)2.
Add five 0s to make a total of eight bits,
(00000111)2.
The integer is stored in the memory location.
30
Example:
Store 258 in a 16-bit memory location.
Solution
First change the integer to binary (100000010)2.
Add seven 0s to make a total of sixteen bits, (0000000100000010)2.
The integer is stored in the memory location.
31
Sign-and-Magnitude
Representation
In this method, the available range for unsigned integers (0 to 2n1)
is divided into two equal sub-ranges.
The first half represents positive integers, the second half, negative
integers.
Noted that there are two different representations for zero.
32
33
34
char is the
smallest integral data type.
char data type is used to represent characters, that is
letters, digits and special symbols.
Each character is enclosed within single quote marks.
Some of the values belonging to char data type are:
'A', 'a', '0', '*', '+', '$', '&
Blank space is a character and is written ' ', with a
space left between the single quotes.
36
37
0 nul
soh
stx
etx
1 lf
vt
ff
cr
2 dc4
nak
syn
etb
3 rs
us
4(
52
6<
enq ack
bel
bs
ht
so si del
dc1
dc2
dc3
em sub
esc
fs
gs
eot
can
&
>
7F
8P
9Z
10
11
12
del
39
Floating Point
A floating-point type is a number with a
fractional part, such as 43.32. The C++
language supports three different sizes of
floating-point: float, double and long double.
sizeof(float)<= sizeof(double)<= sizeof(long double)
float
double
long double
40
41
43
45
Example :
String Position of a Character
in the Sting
"William Jacob"
Position of 'W' is 0.
13
Position of 'i' is 1.
Position of 'c' is 2.
Position of 'k' is 3.
Position of 'e' is 4.
Position of 'y' is 5.
46
Declaration of Enumerated
Types
Consider the colors of the rainbow as an
enumerated type:
enum rainbowColors =
{ red, orange, yellow, green,
blue, indigo, violate }
The identifiers between {
enumerators
} are called
Declaration of Enumerated
Types
Why are the following illegal
declarations?
enum grades{'A', 'B', 'C', 'D', 'F'};
enum places{1st,
2nd, 3rd, 4th};
They do not have legal identifiers in the
list
grades{A, B, C, D, F};
places{first, second, third, fourth};
51
Declaration of Enumerated
Types
As with the declaration of any object
Specify the type name
Followed by the objects of that type
Given:
enum daysOfWeek { Sun, Mon,
Tue,Wed, Thu, Fri, Sat }
Then we declare:
daysOfWeek Today, payDay, dayOff;
52
// note no quotes
workaday += 1;
today++;
I/O
generally not possible to do directly
can be sort of done, indirectly
56
Anonymous Type
does not have an associated type
enum (MILD, MEDIUM, HOT) salsa_sizzle;
values
enum {English, French, Spanish, German, Same
Russian}
foreignLanguages;
59
existing_type_name
new_type_name;
Example:
typedef int Boolean;
Does not really create a new type
is a valuable tool for writing self-documenting
programs
60
Namespaces
Recall use of
using namespace std;
Namespace is another word for scope
In C++ it is a mechanism
programmer creates a "named scope"
namespace std
{
int abs ( int );
. . .
}
61
Namespaces
Identifiers within a namespace can be
used outside the body of the
declaration only if
use scope resolution operator
x = std::abs(y);
a using declaration
using std::abs;
z = abs(q);
a using directive
Namespaces
63
65
addition
subtraction
multiplication
division
Arithmetic Expressions
3 +
2 +
5.6
x +
4
3 * 5
+ 6.2 * 3
2 * 5 + 6 / y
68
69
70
Example 2-4
Arithmetic
Expression
2 + 5
Result Description
13 + 89
102
34 - 20
14
45 - 90
-45
2 * 7
5/2
14
2 In the division 5/2, the quotient is
71
34 % 5
-34 % -5
4 % 6
and
73
Example
Expression
Result
5.0 + 3.5
8.5
3.0 + 9.4
12.4
16.3 - 5.2
11.1
4.2 * 2.5
10.50
5.0/2.0
2.5
74
Order of Precedence
The precedence rules of arithmetic operators are:
*, /, %
are at a higher level of precedence than
+, Operators *, /, and % have the same level of
precedence.
Operators + and - have the same level of
precedence.
75
21
21
15
17
23
+
+
6 + (10 / 4) + 6
(Evaluate *)
6 + 2 + 6
(Evaluate /)
2 + 6
(Evaluate -)
6
(Evaluate first +)
(Evaluate +)
76
Character Arithmetic
8+7 = 15
'8' + '7' = 56 + 55 = 111
'8' + 7 = 56 + 7 = 63
'8' * '7' is undefined in the ASCII character data
set.
77
EXPRESSIONS
78
Example
Some C++ integral expressions:
2 + 3 * 5
3 + x - y / 7
x + 2 * (y - z) + 18
Example
Some C++ floating point expressions:
12.8 * 17.5 - 34.50
x * 10.5 + y - 16.2
79
Mixed Expressions
An expression that has operands of different data
types is called a mixed expression.
A
2 + 3.5
6 / 4 + 3.9
5.4 * 2 13.6 + 18 / 2
80
Example
(a) 3 / 2 + 5.0
= 1 + 5.0
(3 / 2 = 1)
= 6.0
(b) 15.6 / 2 + 5
= 7.8 + 5
= 12.8
(c) 4 * 3 + 7 / 5 25.6
= 12 + 7 / 5 25.6
= 12 + 1 25.6
= 13 25.6
= -12.6
(4 * 3 = 12)
(7 / 5 = 1)
(12 + 1 = 13)
(13 25.6 = 13.0 25.6
= - 12.6)
82
83
Example
static_cast<int>(7.9) = 7
static_cast<int>(3.3) = 3
static_cast<double>(25) = 25.0
static_cast<double>(5+3) = static_cast<double>(8)
= 8.0
static_cast<double>(15)/2 = 15.0/2
= 15.0/2.0
= 7.5
84
static_cast<double>(15/2) = static_cast<double>(7)
= 7.0
static_cast<int>(7.8 + static_cast<double>(15)/2)
= static_cast<int>(7.8 + 7.5)
= static_cast<int>(15.3) = 15
static_cast<int>(7.8 + static_cast<double>(15/2)
= static_cast<int>(7.8 + 7.0)
= static_cast<int>(14.8)
= 14
85
x = 15
y = 23
z = 3.75
Expression
Value
static_cast<int>(7.9 + 6.7)
14
static_cast<int>(7.9)
+ static_cast<int>(6.7)
13
static_cast<double>(y / x) + z
4.75
static_cast<double>(y) / x + z
5.28333
86
INPUT
87
88
Example
const double conversion = 2.54;
const int noOfStudents = 20;
const char blank = ' ';
const double payRate = 15.75;
89
Variable
Example
double amountDue;
int
char
int
string
counter;
ch;
x, y;
name;
90
1.
91
92
Assignment Statement
The assignment statement takes the form
variable = expression;
The expression is evaluated and its value is assigned
to the variable on the left side.
93
Examples 2-13
int I, J;
double sale;
char first;
string str;
I = 4;
J = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day. ";
94
95
96
97
Example 2-14
int a, b, c, d;
int x, y;
Evaluate the expressions -b+(b2-4ac)and -b-(b2-4ac),
and assign the values of these expressions to x and
y, respectively.
The expression b2-4ac appears in both expressions
First calculate the value of this expression and save
its value in d.
Use the value of d to evaluate the expressions as
shown by the following statements:
d = b * b 4 * a * c;
x = -b + d;
y = -b d;
98
99
The statement
cin>>miles;
causes the computer to get a value of the type double and
place it in the memory cell miles.
100
101
Variable Initialization
Assignment statement
Read statement
int feet;
We can initialize feet to a value 35 either by using the
assignment statement
feet = 35;
or by executing the statement
cin>>feet;
C++ does not automatically initialize the variables when
102
they are declared.
Example 2-15
int one, two;
double z;
char ch;
string name;
1. one = 4;
2. two = 2 * one + 6;
3. z = (one + 1) / 2.0;
4. ch = 'A';
5. cin>>two;
6. cin>>z;
7. one = 2 * two + static_cast<int>(z);
8. cin>>name;
9. two = two + 1;
10. cin>>ch;
11. one = one + static_cast<int>(ch);
12. z = one z;
103
of
statement
all
variables
are
104
1. one = 4;
105
2. two = 2 * one + 6;
106
3. z = (one + 1) / 2.0;
Statement 3 first evaluates the expression (one + 1)/2.0 (which evaluates to 2.5)
and then stores the value of the expression into z. After the execution of statement
3, the values are:
107
4. ch = 'A';
Statement 4 stores the character 'A' into ch. After the execution of statement 4, the
values are:
108
5. cin>>two;
Statement 5 reads a number from the keyboard (which is 8) and stores the number
8 into two. After the execution of statement 5, the values are:
109
6. cin>>z;
Statement 6 reads a number from the keyboard (which is 16.3) and stores the
number 16.3 into z. After the execution of statement 6, the values are:
111
8. cin>>name;
Statement 8 gets the next input from the keyboard (which is Goofy) and stores it
into name. After the execution of statement 8, the values are:
112
9. two = two + 1;
113
10. cin>>ch;
Statement 10 reads the next input from the keyboard (which is D) and stores it into
ch. After the execution of statement 10, the values are:
114
115
12. z = one z;
116
117
++count;
or
count++;
increments the value of count by 1.
--count;
or
count--;
decrements the value of count by 1.
118
1.
x = 5;
y = ++x;
2.
x = 5;
y = x++;
Example 2-16
Suppose a and b are int variables.
a = 5;
b = 2 + (++a);
After the second statement a is 6 and b is 8.
119
OUTPUT
The syntax of cout together with << is
cout<<expression or manipulator<<expression or
manipulator...;
Example 2-17
Statement
Output
1. cout<<29/4;
Hello there.
12
4. cout<<"4+7";
4+7
5. cout<<4+7;
11
6. cout<<"A";
7. cout<<"4 + 7 = "<<4 + 7;
8. cout<<2+3*5;
4 + 7 = 11
17
Hello
there.
\n is called new line escape sequence.
\ (back slash) is called the escape character.
121
122
Example 2-18
int a, b, c, d;
a = 65 ;
//Line 1
b = 78 ;
//Line 2
cout<<29/4<<endl; //Line 3
cout<<3.0/2<<endl;
//Line 4
cout<<"Hello there.\n";
//Line 5
cout<<7<<endl; //Line 6
cout<<3+5<<endl;
//Line 7
cout<<"3+5"; //Line 8
cout<<endl;
//Line 9
cout<<2+3*6<<endl;
cout<<"a"<<endl;
//Line 10
//Line 11
cout<<a<<endl; //Line 12
cout<<b<<endl; //Line 13
cout<<c<<'\n'; //Line 14
cout<<d;
//Line 15
cout<<endl;
//Line 16
123
Output of Statement at
7
Line 3
1.5 Line 4
Hello there. Line 5
7
Line 6
Line 7
3+5 Line 8
20 Line 10
a
Line 11
65 Line 12
78 Line 13
6749684 Line 14
4203005 Line 15
124
125
126
127
Example
Example 2-20
129
Example
or
131
Example
The output of the statement
cout<<"The newline escape sequence is \\n"<<endl;
Is
The new line escape sequence is \n
The output of the statement
cout<<"The tab character is represented as \'\\t\'"<<endl;
is
The tab character is represented as '\t
The output of the statement
cout<<"The string \"Sunny\" contains five characters\n";
is
The string "Sunny" contains five characters
132
Prepr
ocessor Directives
Only a small number of operations are explicitly defined in C++.
Many of the functions and symbols that are necessary to run a C++
program are provided as a collection of libraries.
Every library has a name and is referred as a header file. For example,
the descriptions of the functions needed to perform I/O are contained in
the header file iostream.
The descriptions of some very useful mathematics functions such as
power, absolute, sine, etc., are contained in the header file cmath.
Preprocessor directives are commands supplied to the preprocessor.
All preprocessor commands begin with #.
There is no semicolon at the end of these commands since these are
preprocessor commands not C++ commands.
133
#include <headerFileName>
The preprocessor directive
#include <iostream>
causes the preprocessor to include the header file
iostream in the program.
134
#include <iostream.h>
#include <math.h>
135
136
138
139
The statement
int main(void)
means that the function main returns a value of the
type int and it
has no arguments.
The previous statement is equivalent to statement
int main()
141
Declaration Statements
int
a, b, c;
double
x, y;
Executable Statements
Example 2-24
Executable statements:
a = 4; //assignment statement
cin>>b; //input statement
cout<<a<<endl<<b<<endl; //output statement
142
Syntax
Errors in syntax are detected during compilation.
int x;
int y
//Line 1
//Line 2; syntax error
double z; //Line 3
y = w + x;//Line 4 ; syntax error
143
Use of Blanks
In C++, one or more blanks are used to separate
numbers when data is input.
Blanks are also used to separate reserved words and
identifiers from each other and other symbols.
Commas are used to separate items in a list.
144
Semantics
It is quite possible for you to eradicate all syntax errors
in a program and still not have it run. And if it runs it
still may not do what you meant it to do. For example,
2 + 3 * 5
and
(2 + 3) * 5
are both syntactically correct expressions, but have
different meanings.
145
following
two
ways
of
declaring
146
Blank spaces
int a,b,c;
int
a,
b,
c;
Documentation
Comments
Single line comments
Single line comments begin with // anywhere in the
line.
148
Naming Identifiers
const double a = 2.54;
//conversion constant
double x;
double y;
x = y * a;
Consider the following
const double conversion = 2.54;
double centimeters;
double inches;
centimeters = inches * conversion;
Run-together-word
inchperfoot
Run-together-words can be handled either by using CAPS for the beginning of
each new word or underscore just before the new word.
We could use
either
inchPerFoot
or inch_per_foot.
149
Prompt Lines
cout<<"Please enter a number between 1 and 10 and"
<<" press the return key"<<endl;
cin>>num;
151
Example 2-25
Simple Assignment
Compound Assignment
Statement
Statement
I = I + 5;
I += 5;
counter = counter + 1;
sum = sum + number;
counter += 1;
sum += number;
amount=amount*(interest+1);
x = x / ( y + 5);
amount *= interest + 1;
/= y + 5;
153
154
155
156
Variables
int feet;
int inchs;
//in centimeters.
Named Constant
const double conversion = 2.54;
const int inchesPerFoot = 12;
157
Main Algorithm
1. Prompt the user for the input. (Without a prompt
line, the user will be staring at a blank screen
and will not know what to do.)
2. Get the data.
3. Echo the inputthat is, output what the program
read as input. (Without this step, after the
program has executed, you will not know what
the input was.)
4. Find the length in inches.
5. Output the length in inches.
6. Convert the length to centimeters.
7. Output the length in centimeters.
158
Putting it Together
The program will begin with comments that document its purpose and
functionality.
There is both input to this program (the length in feet and inches) and output (the
equivalent length in centimeters), you will be using system resources for
input/output.
The program will use input statements to get data into the program and output
statements to print the results.
The data will be entered from the keyboard and the output will be displayed on
the screen, the program must include the header file iostream.
The first statement of the program, after the comments as described above, will
be the preprocessor directive to include this header file.
159
160
161
162
int main ()
{
//declare variables
int feet;
int inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
cout<<"Enter two integers, one for feet, "
<<"one for inches: ";
cin>>feet>>inches;
//Step 1
//Step 2
cout<<endl;
cout<<"The numbers you entered are "<<feet
<<" for feet "<<"and "<<inches
<<" for inches. "<<endl;
//Step 3
163
//Step 5
//Step 7
return 0;
}
164
165
166
int main ()
{
//declare variables
int feet;
int inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
cout<<"Enter two integers, one for feet, "
<<"one for inches: ";
//Step 1
cin>>feet>>inches; //Step 2
cout<<endl;
cout<<"The numbers you entered are "<<feet
<<" for feet "<<"and "<<inches
<<" for inches. "<<endl;
//Step 3
167
//Step 5
//Step 7
return 0;
}
168
Variables
From the above steps it appears that we will need variables to hold half-dollars,
quarters and so on.
Since we are not going to use the values of half-dollars, quarters and so on in
any calculation, we can simply output them. The only thing that keeps changing
is the change.
int change;
Named Constants
const
const
const
const
int
int
int
int
Halfdollar = 50;
Quarter = 25;
Dime = 10;
Nickel = 5;
172
Main Algorithm
1. Prompt the user for input.
2. Get input.
3. Echo the input by displaying the entered
change on the screen.
4. Compute and print the number of half-dollars.
5. Calculate the remaining change.
6. Compute and print the number of quarters.
7. Calculate the remaining change.
8. Compute and print the number of dimes.
9. Calculate the remaining change.
10.
11.
12.
173
= 25;
174
int main()
{
//declare variable
int change;
//Statements: Step 1 Step 12
cout<<"Enter change in cents: ";
cin>>change;
//Step 1
//Step 2
cout<<endl;
cout<<"The change you entered is "<<change<<endl; //Step 3
cout<<"The number of half-dollars to be returned "
<<"are "<<change / Halfdollar<<endl;//Step 4
change = change % Halfdollar;
//Step 5
175
//Step 7
//Step 8
//Step 9
//Step 10
//Step 11
//Step 12
return 0;
}
176
177
178
Ex:
-6728,
180
182