0% found this document useful (0 votes)
15 views74 pages

Lecture2 DataTypes Variables NumericalOutput

The document discusses data types, variables, and numerical output in C++ programming, emphasizing the importance of variables as storage locations that can change values during program execution, while constants remain fixed. It explains variable declarations, assignments, and the distinction between built-in and class data types, highlighting the need for appropriate data types to ensure correct operations. Additionally, it covers the characteristics of numerical data types, including integer and floating-point types, and their implications for memory usage and precision.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views74 pages

Lecture2 DataTypes Variables NumericalOutput

The document discusses data types, variables, and numerical output in C++ programming, emphasizing the importance of variables as storage locations that can change values during program execution, while constants remain fixed. It explains variable declarations, assignments, and the distinction between built-in and class data types, highlighting the need for appropriate data types to ensure correct operations. Additionally, it covers the characteristics of numerical data types, including integer and floating-point types, and their implications for memory usage and precision.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Types, Variables,

and Numerical Output


CS 52: C++ Programming
 Describe data types
 Add some arithmetic operators to our software
Objectives  Output the numerical answers using cout
 Declare some variables and declarations
 Discover common programming errors
 VARIABLES: represent storage locations in a computer’s memory
 The value of a variable can change while a program is running

 CONSTANTS (LITERALS): data items whose value cannot change


while a program is running
 A fundamental objective of all computer programs is to
manipulate data to solve problems and get some sort of result (or
Variables and answer)
Constants  In order to do this, there must be places in memory to store the data
a program is manipulating

 All data used in a computer program are stored in and retrieved


from the computer’s memory unit
 It used to be that these memory locations were referenced by
their memory address
 You can think of a variable as an "interface" to RAM
 A variable is a name a programmer uses to refer to a computer
storage location (can be used to store or retrieve data from that
location)
 Symbolic names are used in place of memory addresses
 These symbolic names are called variables
 These variables refer to memory locations
More on  The value stored in the variable can be changed (unlike
constants/literals)
Variables  Simplifies programming effort

 Each variable in a program will only store one particular type of


data
 The type of data that can be stored in a variable is fixed once you
define it in your program
 Only the value each variable contains changes during the course of the
program based on the statements in the program
 Part of the job of a programmer is to determine how many variables a
program needs and what type of data/information each variable in a
program will hold
 Example of a C++ program using a variable
#include <iostream>
using namespace std;
int main()
{
Variables int number;
number = 5;
Example cout << "The value of number is " << "number" << endl;
cout << "The value of number is " << number << endl;
number = 7;
cout << "The value of number is " << number << endl;
return 0;
}
 The first line in the program is a variable declaration:
int number;
 A variable declaration tells the compiler the variable’s name and the
type of data it will hold
 The compiler needs to know the name for the memory location you
want to store data in and what amount of storage to set aside (the type
of data determines this)
 Remember a variable is just a name for a memory location to make it easier
Variables for the programmer to reference and use that memory location
 This line indicates the variable’s name is number and the word int
Example (2) stands for integer indicating that number will be used to hold
integer values.
 int is a data type (we'll talk more about them in a bit)
 All variable declarations end with a semicolon (they are
programming statements)
 You must have a declaration for every variable you intend to use in a
program
 You must declare (allocate) a variable (memory location) before you
can use it
 Assignment statement: assigns a value to a variable (this is NOT
the same as math; note the difference)
 Format: variable name = expression;
 In the program: number = 5; number = 7;

Variables  The = sign in an assignment statement is an operator that copies the


value on its right (5 or 7 in this case) into the variable (memory
Example (3) location) on the left
 The right side of the assignment statement is an expression
 Before the expression is copied into the variables on the left side of the
equal sign it is evaluated
 An assignment statement does not print anything to the screen, it
works silently behind the scenes storing a value in RAM
 The next two lines of code in the example program:
cout << "The value of number is " << "number" << endl;
cout << "The value of number is " << number << endl;
 The output these two lines of code produce:
The value of number is number
The value of number is 5
Variables  In the first cout statement the string literal “number” is inserted into the
output stream so the string number is printed
Example (4)  In the second cout statement because there are no quotation marks
around it, it is the variable number that is inserted into the output string
causing its value to be evaluated and printed
 Remember we said the " " around a string were important, now you see
why
 "number" is what's called a string literal

 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  C++ allows only certain operations to be performed on certain


types of data
 Prevents inappropriate programming operations

 DATA TYPE: A set of values and operations that can be applied to


these values
 Example of Data Type: Integers
 The Values: Set of all Integer (whole) numbers
 The Operations: Familiar mathematical and comparison operators
 C++ categorizes data types into two fundamental
categories/groupings
 Class Data Types:
 Usually a programmer-created data type
 But also can be a data type provided by the C++ library such as a string
 Set of acceptable values and operations defined by a programmer
using C++ code
 Requires external code defined by the programmer

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

Built-In Data Types Operations


Integer +, -, *, /, %, =, ==, !=, <=, >=, sizeof(), and
bit operations
Floating Point +, -, *, /, =, ==, !=, <=, >=, sizeof()
 The primary considerations for choosing which numeric data type
to use for a variable in a C++ program are:
Numerical  The largest and smallest numbers that may be stored by the variable
 How much memory the variable uses
Data Types (2)  Whether the variable holds signed or unsigned numbers
 The number of decimal places of precision a variable has
 C++ provides nine built-in Integer Data Types
 This is a lot more than in Java

 Three most important Integer Data Types


Integer Data  int
 char
Types  bool (this is similar to Boolean in Java)

 Reason for remaining 6 Integer data types is historical


 Originally provided for special situations
 Difference among types based on storage requirements
 C++ provides nine built-in Integer Data Types
 The values of the columns Size and Range depend on the system the
program is compiled for
 This is different than in Java
Name of Data Storage Size Range of Values
Type (in bytes)

Integer Data char


bool
1
1
256 characters
True (any positive value) or false (value is zero)
Types (2) short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
 Set of values supported are whole numbers
 Whole numbers mathematically known as integers
 The value zero or any positive or negative numerical value without a
decimal point
int
 An integer consists of digits only and can be optionally preceded
by either a plus (+) or a minus (-) sign
 Commas, decimal points, and special signs not allowed
 Examples of int:
 Valid: 0 5 -10 +25 1000 253 -26351 +36
 Invalid: $255.62 2,523 3. 6,243,982 1,492.89

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 + $ . , - !

 Single Character Value: any one letter, digit or special character


enclosed in single quotes
char  Examples: ‘A’ ‘$’ ‘b’ ‘7’ ‘y’ ‘!’ ‘M’ ‘q’

 The single quotes are essential


 This is the only way the compiler knows you are talking about a
character literal and are saving the right type of data into a char type
variable
 Character values are typically stored in a computer using either
the ASCII or Unicode codes
 ASCII, pronounced AS-KEY, is an acronym for American Standard
Code for Information Interchange.
 The ASCII code provides codes for an English-language-based
char (2) character set plus codes for printer and display control, such as new
line and printer paper-eject codes
 Each character code is contained within a single byte, which
provides for 256 distinct codes
 ASCII: American Standard Code for Information Exchange
 Basically ASCII is just a table that tells which character is represented by which
pattern of bits
 Provides English-language based character set plus codes for printer and display
control
 Each character code contained in one byte
 256 distinct codes
 A char is a numerical data type because each of the 256 characters are
represented by a binary code
 These binary codes represent on thing if interpreted as a number and another if

ASCII and interpreted as a char


 This can be used to the programmers advantage as we'll see later
 Notice that each character in the ASCII table is represented by a numeric (decimal)
Unicode value
 So the character 'A' is represented by the decimal value 65
 The following two statements both set the variable ch to the character 'A'

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

Character  Escape Sequence: combination of a backslash and specific


characters with no intervening white space which causes the
compiler to create a single ASCII code
 Example: newline escape sequence, \n
Escape Character Meaning ASCII
Sequence Represented Code
\n New line Move to a new line 00001010
\t Horizontal tab Move to next horizontal tab setting 00001001
\v Vertical tab Move to next vertical tab setting 00001011
\b Backspace Move back one space 00001000

The Escape \r Carriage return Moves the cursor to the start of the
current line; used for overprinting
00001101

Character (2) \f Form feed Issue a form feed 00001100


Escape Character Meaning ASCII
Sequence Represented Code
\a Alert Issue an alert (usually a bell sound) 00000111
\\ Backslash Insert a backslash character (this is used 01011100
to place an actual backslash character
within a string)
\? Question mark Insert a question mark character 00111111
The Escape \’ Single Insert a single quote character (this is 00100111
quotation used to place an inner single quote
Character (3) mark within a set of outer single quotes)
\” Double Insert a double quote character (this is 00100010
quotation used to place an inner double quote
mark within a set of outer double quotes)
\nnn Octal number The number nnn (n is a digit) is to be --------
considered an octal number
\xhhhh Hexadecimal The number hhhh (h is a digit) is to be --------
number considered a hexadecimal number
\0 Null character Insert the null character, which is 00000000
defined as having the value 0
 Both ‘\n’ and “\n” represent the newline character
 ‘\n’ is a character literal
 “\n” is a string literal

 Both cause the same thing to happen but are translated


differently
The Escape  A new line is forced on the output display

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’

 Think of an array for now as a data structure that can hold


primitive data values of the same type
 So while “A” prints the same thing to an input device as ‘A’ the two
are not the same data type
 This also means that trying to print a string to an output device by
enclosing it in single quotes instead of double quotes would cause
an error ‘A string literal should not go in single quotes’
 Another error would be to confuse the numeric value 5 with the
Some string literal "5" or the character value '5'.
 int number = ‘5’ or int number = “5” are incorrect variable definitions
Programming because ‘5’ and “5” are not integer literals/constants but are string
and character literals/constants which are completely different data
Tips (2) types

 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++

 Often used when a program must examine a specific condition


The bool Data  If condition is true, the program takes one action, if false, it takes
another action
Type  The bool data type uses an integer storage code
 Zero represents a false value and all other positive integer values
represent a true value
 Note that this is different than in Java where the Boolean data type
only takes on the values of true and false
 Note that bool can only take unsigned values
#include <iostream>
using namespace std;

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)

Example << "\nbool


<< '\n';
" <<sizeof(bool)

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

 Binary operators: require two operands


 The operands can be a literals or identifiers (or a literal and an
identifier)
Arithmetic
 Binary Arithmetic Expression: one consisting of an operator
Operators (2) connecting two operands which can be variables or literals
 Format: literalValue operator literalValue

variable operator variable


variable operator literalValue
literalValue operator variable
 Rules for evaluating arithmetic expressions
 If both operands are integers: result is integer
 If one operand is floating-point: result is floating-point

 Mixed-mode Expression: arithmetic expression containing integer


and non-integer (real/floating point) operands
 The result of a mixed mode expression is always a floating-point
Arithmetic value

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

 Uses same sign as binary subtraction (-)


 Frequently we will want to create complex arithmetic expressions
in C++ that contain multiple operands and operators
 Rules for expressions with multiple operators
 Two binary operators cannot be placed side by side
 5-+6

Operator  Parentheses may be used to form groupings


 Expressions within parentheses are evaluated first
Precedence  Sets of parentheses may be enclosed by other parentheses
 Evaluate the expressions in the innermost parenthesis first and work
your way outwards
 The number of left parentheses must always equal the number of right
parentheses
 Parentheses cannot be used to indicate multiplication
(multiplication operator (*) must be used)
 Order of evaluation for complex arithmetic expressions
 Evaluate expressions in parenthesis first from the innermost
parenthesis to the outermost
 What about parts of the expression not in parenthesis?
 Evaluate parts of the expression not in parenthesis according to
operator precedence (priority) rules
Operator  Operator precedence in C++
 All negations are done first
Precedence (2)  Multiplication, division, and modulus operations are computed next
 Expressions containing more than one multiplication, division, or
modulus operator are evaluated from left to right as each operator is
encountered
 Addition and subtraction are computed last
 Expressions containing more than one addition or subtraction are
evaluated from left to right as each operator is encountered
 OPERATOR ASSOCIATIVITY: refers to the order of which
operators of the same precedence are evaluated
 For addition, subtraction, multiplication, division, and modulus, the
Operator associativity is left to right
Associativity  For the unary +/– (positive/negative) operator, the associativity is
right to left
 cout allows for display of result of a numerical expression
 Display is on standard output device

 Example: cout << “The total of 6 and 15 is ” << (6 + 15);


 Statement sends two pieces of data: a string and a value to be sent
to cout
Numerical  String: “The total of 6 and 15 is ”
 Value: value of the expression 6 + 15
Output Using  The parenthesis are not required to indicate that is the value of the
expression that is being placed in the input string.
cout  Display produced: The total of 6 and 15 is 21

 Individually each set of data sent to cout is preceded by its own


insertion symbol (<<)
 Notice the space after the is in the string, without this the value 21
would come right after the “s” (i.e. The total of 6 and 15 is21)
 The insertion of data onto the output stream can be made over
multiple lines and is terminated only by a semicolon
 The rules for using multiple lines are that a string contained within
double quotes cannot be split across lines and that the
terminating semicolon must only appear on the last line
 Legal
Numerical cout << “The total of 6 and 15 is ”
Output Using << (6 + 15);
 Illegal
cout (2) cout << “The total of 6 and
15 is ” << (6 + 15);
 Illegal
cout << “The total of 6 and 15 is ”;
<< (6 + 15);
 Floating point values are displayed with significant digits to the
right of the decimal place to accommodate the number
 This is true if the number has six or fewer significant digits
 More than six significant digits, fractional part is rounded to six
significant digits
Numerical  Zero significant digits displays no decimal point or significant digits

Output Using  Example:


cout << “15.0 * 2.0 equals ” << (15.0 * 2.0) << endl;
cout (3)  Output: 15.0 * 2.0 equals 30

 NOTE: In this example the output is 30 because cout formatted it


that way….what data type is the 30?
 ANSWER: It's still floating point even though it may appear C++ has
converted it to an integer
 A program should present results attractively
 Field width manipulators: control format of numbers displayed by
cout
 Manipulators are included in the output stream
 Field width manipulators are useful in printing columns so that the
Formatted numbers in each column align correctly

Output  The setw(n) field manipulator sets the field width to n


 The setw(n) manipulator should be place before the numeric field it
is manipulating in the output stream

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

Integers << setw(3) << 18 << endl


<< setw(3) << 124 << endl
Example << "---\n"
<< 6+18+124 << 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 {

Output – cout << fixed << setprecision(2)


<< setw(6) << 6.1 << endl
Floating Point << setw(6) << 18.2 << endl

Example #2 << setw(6) << 124.0 << endl


<< "------\n"
<< 6.1+18.2+124<< endl;

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

Common  Using a variable in an expression before the variable is assigned a


value
Programming  Dividing integer values incorrectly mixing data types in the same
Errors expression without clearly understanding the effect produced
 It is best not to mix data types in an expression unless a specific
result is desired

 Forgetting to separate individual data streams passed to cout with


an insertion (<<) symbol
 Four basic types of data recognized by C++:
 Integer
 Floating-point
 Character
 Boolean
Summary  cout object can be used to display all data types
 Every variable in a C++ program must be declared as the type of
variable it can store
 Reference variables can be declared that associate a second name
to an existing variable
 DECLARATION STATEMENTS: inform the compiler of function’s
valid variable names
 DEFINITION STATEMENTS: declaration statements that also
Summary (2) cause computer to set aside memory locations for a variable
 sizeof() operator: determines the amount of storage reserved for a
variable

You might also like