Lecture2 DataTypes Variables NumericalOutput
Lecture2 DataTypes Variables NumericalOutput
This part of the code illustrates both the string literal (constant)
number and the variable number
Let’s look at the formal definition for a literal
CONSTANT: Acceptable value for a data type
Value explicitly identifies itself
Remember from your intro programming class that all data in a
computer is represented by 1s and 0s, in order for data in a
Constants computer to have meaning in a program the TYPE of data MUST be
identified
(Literals) A combination of 1s and 0s for a string data type means something
totally different for a numeric data type
Variables are going to be set up to be a certain data type and will only
be able to hold data of that type….this type tells the compiler how to
interpret the 1s and 0s
A constant is a value of a specific type
Numeric constants
The numbers 2, 0, and -20 are constants of type int
The numbers 2.1 and -3.75 are constants of type double
The number 2.1f is a constant of type float
Why the f? Because a fractional number is automatically considered to be
of type double to the compiler so to make it of type float you need to add
the f
Constants String constants
(Literals) (2) The text “Hello World!” is a string constant
A string can be thought of as a sequence of characters (we'll discuss this
more in a later lecture)
Notice the string constant is enclosed in double quotes
When you use a string constant in a cout statement the text itself is
displayed
Character constants
Notice the character constant is enclosed in single quotes
'a' , 'A' , 'b' , 'B' are examples of character constants
Constants are also known as literal values and literals
An example of a non-constant value would be a value that does
not display itself but that is stored and accessed using an identifier
Constants (a variable)
While constants are used in programs it is more common for a
(Literals) (3) program to use a variable
When you use a variable in a program you must decide what data type
to associate with that variable
Variables can change during the course of the program while constants
cannot
From the previous example program
Looking Back Notice that the string constant “number” is not the only
literal/constant used in the example program
at the 5 and 7 are integer constants (literals)
Variables Notice we're saving constant of type integer (int) into a variable of type int
“The value of the number is” is a string literal
Example “number” in the second cout statement is a string literal
0 is an integer constant
The next two lines of code in the example program:
number = 7;
Looking Back cout << "The value of number is " << number << endl;
at the The first line of code replaces the previous value stored in the
Variables variable number with a seven
A variable can only store one value of its declared type at a time
Example (2) The output this cout line of code produces:
The value of number is 7
This part of the code illustrates that the value of a variable can be
Looking Back changed during the course of the program
at the When put a VARIABLE in a cout stream the compiler finds the
value in that variable and displays it as a string
Variables
QUESTION: So how does the compiler know we mean the
Example (3) variable number and not the string "number"?
A variable declaration is a program statement that specifies the name
of a variable of a given type in a program
int number;
is an example of a variable declaration that declares a variable with the
name number that can store integers
A variable declaration statement has the following general form
dataType variableName;
Variable A variable declaration statement always ends with a semicolon – in
order to interpret data, the compiler must know where the data is
(variable name) and what type it is (how to interpret it, is it an integer? a
Declaration string? a character? etc.)
A single variable declaration can specify the names of several
variables:
int number1, number2, number3;
However, for clarity in your programs it is generally better to declare
each variable on a single line
If I ever declare more than one variable on a line in this class it is only to save
space, in a real program I would always declare each variable on a separate
line
Variables can be declared anywhere in your program but a variable
must be declared before it can be used – the compiler reads
statements sequentially and cannot skip ahead in the program
It is standard practice to declare variables at the top of the function
they are being used in whenever this is possible
Use standards
Variable Variable Declaration vs. Variable Definition
Declaration (2) In order to store data in memory you need to not only have defined
the name and type of your variable but you need to have associated
a piece of the computer's memory with the variable name
The process of associating a piece of the computer's memory with the
variable name is called variable definition
In C++ a variable declaration is in most cases also a variable definition
So in the course of a single statement, we introduce the variable name and
tie it to an appropriately sized piece of memory
When you declare a variable you can also assign an initial value to
it
A variable declaration that assigns an initial value to the variable is
called an initialization
Remember as long as a variable doesn't have an initial value in it, it
contains garbage, NOT nothing (it is impossible for a variable to
Variable contain nothing)
To initialize a variable when you declare it, write and equals sign
Initialization after the variable declaration followed by the value you would like
to initialize the variable to:
int number = 1;
double value = 3.5;
Good programming practice is to declare each initialized variable on
a line by itself
NOTE: If you don't supply an initial value for a variable in C++, it
will contain whatever garbage was in the variable's location before
the program ran
This is not like Java where the compiler will give you an error if you
Variable fail to initialize a variable, in C++ the compiler will just use the
garbage values
Initialization Whenever possible, you should initialize your variables when you
(2) declare them
If your variables start with initial values, it will be easier to find errors
when things go wrong in your program
The C++ compiler is much less generous in helping you find these kind
of errors than the Java compiler is
Let's look closer at the form of a variable declaration
A variable declaration statement has the following general form
dataType variableName;
The second part of the variable declaration statement is the
variableName
Variable A variable name is an identifier (a user defined name that
Declaration represents some element of a program)
To be legal a variable name must follow the rules of a legal identifier
we discussed in the last chapter
An identifier must begin with a letter or underscore_
Each character after the first character of an identifier must be a letter,
digit, or underscore_
The variable name cannot be a keyword
The first part of the variable declaration statement is a data type
Variables are classified according to their data type which
determines the type of information that may be stored in them
Variable For example variables with integer data types can only hold whole
numbers
Declaration (2) In order to decide which data type to use for a variable you need to
understand more about data types
We will go over this next
The objective of all programs is to process data
It is necessary to classify data into specific types
Numerical
Alphabetical
Audio
Video
Data Types (2) The majority of the operations on class data types are user defined
functions
Built-In Data Types
Provided as an integral part of C++
Also known as a primitive type
Requires no external code
Consists of basic numerical types
Majority of operations are symbols (e.g. +,-,*,…)
This is in contrast to class data types where the majority of the operations
are provided as functions
In a very broad sense there is only one category of built in data
type: numerical data types
Numerical There are two categories of numerical data types
Integer data types
Data Types Floating point data types
int (2) Different compilers have different internal limits on the largest
and smallest integer values that can be stored in each data type
The most common allocation for the int
4 Bytes, which restricts the set of values represented by the int data
type to the range -2,147,483,648 to 2,147,483,647
Used to store individual (single) characters
Letters of the alphabet (upper and lower case)
Digits 0 through 9
Special symbols such as + $ . , - !
char ch = 'A';
char ch = 65;
Unicode: Provides other language character sets
Each character contained in two bytes
Can represent 65,536 characters
First 256 Unicode codes have same numerical value as the 256 ASCII codes
#include <iostream>
using namespace std;
int main()
{
char ch1 = 65; //The ASCII code 65 represents the
char Example character 'A'
char ch2 = 'A';
cout << "The value of ch1 is " << ch1 << endl;
cout << "The value of ch2 is " << ch2 << endl;
return 0;
}
Backslash ( \ ): the escape character
Special meaning in C++
Placed before a select group of characters, it tells the compiler to
The Escape escape from normal interpretation of these characters
The Escape \r Carriage return Moves the cursor to the start of the
current line; used for overprinting
00001101
Character (4) In translating the ‘\n’ the compiler translates it using the ASCII
code
In translating the “\n” the compiler translates the correct code but
also adds a string termination character ‘\0’
Good programming practice is to end the final output display with
a newline escape sequence
It’s important to under stand the difference between a character, a
string, and a numerical value
‘A’ and “A” both display the character A on an output device
‘A’ is a character literal which represents a single character
Some “A” is a string literal
Programming A string is an array of characters (if you don't know what an array is
think of it as a sequence of characters) terminated with a null character
Tips ‘\0’
You can only save data of the CORRECT TYPE into a variable
So an int variable can ONLY hold integer types
A char variable can NOT hold STRINGS
etc.
Represents Boolean (logical) data
Restricted to true or false values
These true/false values are represented by integers in C++
int main()
{
bool boolF = 0; //a bool data type with a value of zero is false
Boolean bool boolT = 2; //a bool data type with any value other than zero is true
Example cout << "The value of boolF is " << boolF << endl; //A zero value for
bool represents false
cout << "The value of boolT is " << boolT << endl; //A 1 value for bool
represents true
return 0;
}
C++ makes it possible to see how values are stored
Remember the number of bytes used to store a data type is compiler
Determining dependent
Storage Size sizeof(): provides the number of bytes required to store a value for
any data type
Built-in operator that does not use an arithmetic symbol
#include <iostream>
using namespace std;
int main()
{
cout << "\nData Type Bytes"
Determining << "\n--------- -----"
<< "\nint " <<sizeof(int)
Storage Size << "\nchar " <<sizeof(char)
return 0;
}
The output of this program is compiler dependent
Each compiler will correctly report the amount of storage it provides for the data type under
consideration
SIGNED DATA TYPE: stores negative, positive and zero values
Signed and UNSIGNED DATA TYPE: stores positive and zero values
Provides a range of positive values double that of unsigned
Unsigned Data counterparts
Types char and bool are unsigned data types
No codes for storing negative values
Some applications only use unsigned data types
Example: date applications in form year month day
Signed and For these type of applications an unsigned data type could be used
Unsigned Data All unsigned data types provide a range that is basically double
the range for their signed counterpart
Types (2) This extra positive range is made available by using the negative
range of the data type’s signed version for additional positive
numbers
The other built in numerical data type (other than Integer types) are
Floating-Point data types
Remember we are talking about BUILT IN DATA types, ones provided by
the compiler rather than created and written by programmers
(sometimes stored in libraries, sometimes not)
A floating point number can be the number zero or any positive or
negative number that contains a decimal point
Also called real number
Floating Point Examples: +10.625 5. -6.2 3521.92 0.0
5. and 0.0 are floating-point, but same values without a decimal (5, 0)
Types would be integers
As with integer values special symbols such as the dollar sign or the
comma are not permitted
C++ supports three floating-point types:
float
Double
long double
Different storage requirements for each
Most compilers use twice the amount of storage for a double as
for a float which allows a double to have approximately twice the
precision as a float
For this reason a float is often called a single precision number and a
Floating Point double a double precision number
Types (2) The actual storage for each type does differ by compiler
Currently most C++ compilers allocate four bytes for a float and eight
bytes for both the double and long double types
In compilers that allocate the same number of bytes for double and long
double these types become identical (try sizeof())
PRECISION: refers to the numerical accuracy or number of
significant digits
Significant digits = number of correct digits + 1
Remember the last digit is rounded
Floating Point Significant digits in a number may not correspond to the number
Types (2) of digits displayed
Example: if 687.45678921 has five significant digits, it is only
accurate to the value 687.46
So the significant digits are accurate to the value 687.46 and the last
digit is rounded
Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Modulus %
Arithmetic
Operators
Operators for numerical data types (primitive/built in data types)
Remember data types are the set of values AND the operations that
can be performed on those values
Operators (3) Note that the arithmetic operations for addition, subtraction,
multiplication and division are implemented differently for integer
and floating point arithmetic
This means that the type of arithmetic performed depends upon the
type of operands in the expression
This means the arithmetic operators are overloaded
OVERLOADED OPERATOR: a symbol that represents more than
one operation
Division of two integers yields an integer
Integers cannot contain a fractional part - results may seem
Integer strange
Division In C++ the fractional part of the result obtained when two integers
are divided is simply dropped (truncated)
Example: integer 15 divided by integer 2 yields the integer result 7
#include <iostream>
using namespace std;
int main()
{
Integer int num1 = 15;
Division int num2 = 2;
Example cout << "Integer Division 15/2 = " << num1/num2 << endl;
cout << "Integer Division 2/15 = " << num2/num1 << endl;
return 0;
}
We may want to calculate the remainder of integer division; this is
Remainder done with the modulus operator
Division – Modulus Operator (%): captures the remainder
Also called the remainder operator
Modulus (%) Example: 9 % 4 is 1 (i.e. remainder of 9/4 is 1)
#include <iostream>
using namespace std;
int main()
Remainder {
int num1 = 9;
Division – int num2 = 4;
Modulus (%)
Example cout << "Remainder Division 9%4 = " << num1%num2 << endl;
cout << "Remainder Division 4%9 = " << num2%num1 << endl;
return 0;
}
A unary operation that negates (reverses the sign of) the operand
Unary refers to the fact that this arithmetic operation only takes one
Negation operand
cout << “The sum of 6 and 15 is” << setw(3) << 21;
This field width setting causes the 21 to be printed in a field of three
spaces which includes one blank space and the number 21
#include <iostream>
using namespace std;
int main ()
{
Unformatted cout << 6 << endl
Output << 18 << endl
<< 124 << endl
Example
<< "-- - \n"
<< (6 + 18 + 124) << endl;
return 0;
}
Output
6
Unformatted 18
124
Output
---
Example (2) 148
You would use the setw(n) manipulator to format this output to be
right aligned
#include <iostream>
#include <iomanip>
using namespace std;
int main()
Formatted {
Output – cout << setw(3) << 6 << endl
return 0;
}
To use the field width manipulators you must include the proper
header file in the program which is #include <iomanip>
Formatted Output is right aligned as expected
Output – The field width manipulator must be included for each number
inserted into the data stream sent to cout and a particular setw
Integers manipulator only applies to the next insertion of data immediately
following it
Example (2)
Could take out manipulator in front of 124 since 124 automatically
already has a field width of 3
A formatted floating point number requires the use of three field
width manipulators
Formatted The setw(n) manipulator to set the total width of the display
Output – The fixed manipulator to force the display of the decimal point
The setprecision(n) manipulator to determine how many digits will
Floating Point be displayed to the right of the decimal point
Numbers are rounded to this number of decimal places
Unlike setw(n), the fixed and setprecision(n) field width
manipulators can be used once in a cout statement and then will
Formatted be applied to all other floating point output following their use
Output – In a floating point number, the decimal point counts as one field
place when using setw(n)
Floating Point With both floating point and integer numbers, if the field set in
(2) your setw(n) manipulator is not large enough to hold your number
the field width is automatically expanded to accommodate your
number
cout << setw(10) << fixed
<< setprecision(3) << 25.67;
Formatted
Output: 25.670 (right aligned, spaces fill up 4 unused fields in the
Output – total field width of 10)
Floating Point These are the main field width manipulators we will be using, but
there are more you can use to make your output even more
Example formatted or formatted in different ways
#include <iostream>
#include <iomanip>
using namespace std;
int main()
Formatted {
return 0;
}
Manipulators Number Display Comments
setw(2) 3 | 3| Number fits in field
setw(2) 43 |43| Number fits in field
setw(2) 143 |143| Field width ignored
Formatted setw(2) 2.3 |2.3| Field width ignored
setw(5) 2.366 | 2.37| Field width of 5 with 2 decimal digits
Output – fixed
Floating Point setprecision(2)
setw(5) 42.3 |42.30| Number fits in field with specified precision
Effect of fixed
setprecision(2)
Manipulators setw(5) 142.364 |1.4e+002| Field width ignored and scientific notation
fixed used with the setprecision manipulator
setprecision(2) specifying the total number of significant
digits (integer plus fractional)
Forgetting to declare all variables used in a program
Attempting to store one data type in a variable declared for a
different type