Download - Computer Science stuff, chapter 1
-
8/8/2019 Computer Science stuff, chapter 1
1/104
1
Chapter 1: C++ Basics
-
8/8/2019 Computer Science stuff, chapter 1
2/104
2
Contents
C++ Program
Assignment Statement
Arithmetic Expressions
Simple Input and Output
Type Casting
Operators
-
8/8/2019 Computer Science stuff, chapter 1
3/104
31-3
Learning Objectives
Introduction to C++
Origins, Object-Oriented Programming, Terms
Variables, Expressions, and AssignmentStatements
Console Input/Output
Program Style Libraries and Namespaces
-
8/8/2019 Computer Science stuff, chapter 1
4/104
4
#include
using namespace std;
int main()
{
variable declarations;
statements;
return 0;}
C++ Program Structure
Zero or more variabledeclarations
One or morestatements
No semicolon
-
8/8/2019 Computer Science stuff, chapter 1
5/104
5
A Simple C++ Program
#include
using namespace std;
int main()
{
// nothing to declare
cout
-
8/8/2019 Computer Science stuff, chapter 1
6/104
6
Running C++ in Unix
linux02> ls
exam1.cpp
-
8/8/2019 Computer Science stuff, chapter 1
7/104
7
Running C++ in Unix
linux02> ls
exam1.cpp
linux02>more exam1.cpp#include
using namespace std;
int main(){cout
-
8/8/2019 Computer Science stuff, chapter 1
8/104
8
Running C++ in Unix
linux02> ls
exam1.cpp
linux02>more exam1.cpp#include
using namespace std;
int main(){cout
-
8/8/2019 Computer Science stuff, chapter 1
9/104
9
Running C++ in Unix
linux02> lsexam1.cpp
linux02>more exam1.cpp#include
using namespace std;
int main(){
cout
-
8/8/2019 Computer Science stuff, chapter 1
10/104
10
Preprocessor Directive
#include is a preprocessor directive.
All preprocessor directives start with the # symbol which
must be in the first character position on the line. This preprocessor directive tells the preprocessor to
copy (include) the file into this program file
before the program is compiled. The file contains information about
console input/output that is needed by the compiler in
order to correctly compile any C++ program that doesinput and/or output.
Since every program does output this preprocessor
directive will occur in every C program.
-
8/8/2019 Computer Science stuff, chapter 1
11/104
11
Namespaces
using namespace std; is a declaration that tells the
compiler that all the identifiers (names) in the std
namespace can be used in the program. All the names in iostreamamong others are in this
namespace. Without this declaration (for newer
compilers) one would have to put std::name
in front ofall names from this space.
For example here is a typical output instructioncout
-
8/8/2019 Computer Science stuff, chapter 1
12/104
12
Namespaces
Namespaces were introduced into C++ to allow thesame identifiers to be used with different meanings in
different parts of a program by placing them in differentnamespaces.
In real world, many people may be involved in a programmingproject.
Namespace is a way to minimize the interference of separatecomponents.
In this course we will not create any namespaces in our
program so we just always use this declaration in all ourprograms without any further thought.
-
8/8/2019 Computer Science stuff, chapter 1
13/104
13
Namespaces
Namespace: std
x
jphone
Namespace: myspace
yi
jmyphone
std::j myspace::j
-
8/8/2019 Computer Science stuff, chapter 1
14/104
14
Main()
int main() says that main is a function that returns an
integer value.
Every C++ program must have a main function. This iswhere execution starts in every C++ program.
All other functions are called from main() directly or
indirectly.
maina
b
c
-
8/8/2019 Computer Science stuff, chapter 1
15/104
15
Blocks and Indentations
Curly brackets, { }, are used to show the beginningand end of the main function. In general they are used togroup statements into a block.
Spacing and indentation are not required in C, but areextremely important to make the program easier for ahuman to read.
Free format, Spaces are used to separate language components.
The layout of a simple program should be as shown with
the variable declarations and statements indented.
-
8/8/2019 Computer Science stuff, chapter 1
16/104
16
Example: Readable
#include
using namespace std;
int main()
{
int numberOfLanguages;
cout
-
8/8/2019 Computer Science stuff, chapter 1
17/104
17
Example: No indentation
#include
using namespace std;
int main()
{
int numberOfLanguages;
cout
-
8/8/2019 Computer Science stuff, chapter 1
18/104
18
Example: Not readable
#include
using namespace std;
int main()
{int numberOfLanguages; cout
-
8/8/2019 Computer Science stuff, chapter 1
19/104
19
#include
using namespace std;
int main()
{
{
{
}
}
{
}}
Block Structures
Proper Nesting:
Improper Nesting:
-
8/8/2019 Computer Science stuff, chapter 1
20/104
20
Return
The statement return 0 terminates the main functionand returns 0 to the operating system.
The 0 notifies the operating system that termination wasnormal. The return value is typically 0 but does not haveto be 0.
This is the way the main function should always end,
although some programmers leave this statement outsince it only returns a value to the operating system andis thus not absolutely required.
You should simply put it at the end of every mainfunction without further thought.
-
8/8/2019 Computer Science stuff, chapter 1
21/104
21
Simple Rules
C++ is case sensitive. You must write such things as #include , intmain(), return, etc. in lower case as shown.
The following identifiers are different: rate, Rate, RATE.
Finally note that there are no semicolons after the#include , int main() or curly
brackets.
Semicolons end each declaration and statement, but arenot used elsewhere.
In C, semicolons are used as terminators. In someother languages, semicolons may be used asseparators.
-
8/8/2019 Computer Science stuff, chapter 1
22/104
22
Example (code)
/*The world famous hello world program*/
#include
using namespace std;int main()
{
cout
-
8/8/2019 Computer Science stuff, chapter 1
23/104
23
Note
This program (Hello World) is world famous because itwas the first program in the first book on C by Kernighan
and Ritche. It has been traditional ever since to use this as the first
program in books on C/C++/Java and many other
textbooks. A system("PAUSE"); is added so we can see what is
going on in the program. (Example 1-1a).
The systemfunction is in the C standard library, so wehave to include that: #include .
http://../CPP/ch01/exam1-1a.cpphttp://../CPP/ch01/exam1-1a.cpp -
8/8/2019 Computer Science stuff, chapter 1
24/104
24
Comments
The first line of the program/*The world famous hello world program*/
is a comment.
Comments in C++ must start with /* and end with */and can extend over as many lines as desired.
They convey information to the reader of the program
and are ignored by the C++ compiler. There is a new style of comment also allowed in C++,//comment. This type of comment only extends to theend of the line. The above comment could be written as
//The world famous hello world program
-
8/8/2019 Computer Science stuff, chapter 1
25/104
25
Double Character Symbols
Programming languages typically uses many specialsymbols. However we have only a limited number of
symbols on the keyboard. Solution: use multiple character to represent a symbol. /*
-
8/8/2019 Computer Science stuff, chapter 1
26/104
26
More on the Example
cout
-
8/8/2019 Computer Science stuff, chapter 1
27/104
27
Variables
A variable in C++ is an entity that can store a value of aspecified type.
The C++ compiler associates each variable with enoughbytes of memory to store values of the stated type.
The programmer chooses the names of variables. Thesenames can consist of letters (a-z, A-Z), digits (0-9), and
the underscore symbol (_) and must not start with a digit. Examples of variable names are: i, sum,testAverage, x1, high_score.
C++ programmers traditionally use lower case letters invariable names except for the first letter of a subsequentpart of a name made up of parts as illustrated in thename testAverage.
-
8/8/2019 Computer Science stuff, chapter 1
28/104
28
Identifiers
An identifier is an entity that can be used as a variable, afunction name, and some other components of a
program. A C++ identifier can be of any length, although some
compilers will ignore characters after a certain length. thisIsAVeryLongVariableName1
thisIsAVeryLongVariableName2
-
8/8/2019 Computer Science stuff, chapter 1
29/104
29
Variable Types
There are many types in C++. Three of the mostcommonly used types are int (integer - whole numbers - stored in 2 or 4 bytes),
double (real number with a decimal point stored in 8 bytes)
and
char (character - stored in 1 byte). Variable declarations have
the form
A variable declaration can declare a single variable or alist of several variables.
type variable; type list-of-variables;
type list-of-variables-with-initial-values;
-
8/8/2019 Computer Science stuff, chapter 1
30/104
30
Examples
int i;
double x;
char ch;
int score, sum, largestScore;
double cost, tax, avg;
char ch1, ch2;
type variable
List of variables
-
8/8/2019 Computer Science stuff, chapter 1
31/104
31
Examples
int i = 0;
// declares the variable i and gives it the initial value 0
double x = 0.0;
// declares the variable x and gives it the initial value0.0
char ch = A;
// declares the variable ch and gives it the initial value
Aint score = 1, sum = 0, largestScore;
// declares 3 variables and gives 2 initial values
Variable withinitialization
List of variables with orwithout initializations
-
8/8/2019 Computer Science stuff, chapter 1
32/104
32
Simple Types (1 of 2)
1-32Copyright 2008 Pearson Addison-Wesley. All rights reserved.
-
8/8/2019 Computer Science stuff, chapter 1
33/104
33
Simple Types (2 of 2)
-
8/8/2019 Computer Science stuff, chapter 1
34/104
34
Note on quotes
There is no difference between the left quote and theright quote. It looks different in the powerpoint.
The same applies to single quotes xxx, xxx. Microsoft Powerpoint and Word automatically changed
them to left- and right- pairs. If you copy some code from
these slides, you may have to change them back. On the same issue, Powerpoint also change the first
character of a sentence to upper case. There may besome variable i displayed as I in the note.
E l
-
8/8/2019 Computer Science stuff, chapter 1
35/104
35
Example
The compiler associates each variable with enough memory to storevalues of the given type. The value of a variable is stored in theassociated memory.
For example, if after the declaration of variables i, x and ch thecompiler has associated i with the 2 bytes 202-203 and x with the 8bytes 204-211 and ch with byte 212 then the picture of memorywould be as follows.
Here the values are shown in decimal notation as we think of them,but inside the computer they would be in some form of binaryrepresentation for the same numbers.
202 204 206 208 210 212 214address
279.1234567895432 B
A i S
-
8/8/2019 Computer Science stuff, chapter 1
36/104
36
Assignment Statement
The assignment statement always has the form:
variable = value;
The symbol = is the assignment operator in C++. It tells the computer to store the value on the right as thenew value of the variable, i.e. store the value in thememory associated with the variable.
The value can either be a simple value or a value to becomputed (an expression).
It does not mean equal. (e. g. n = n+1; read it as
assign n+1 to n)
D t A i t R l
-
8/8/2019 Computer Science stuff, chapter 1
37/104
371-37
Data Assignment Rules
Compatibility of Data Assignments
Type mismatches
General Rule: Cannot place value of one type into variable ofanother type
intVar = 2.99; // 2 is assigned to intVar!
Only integer part "fits", so thats all that goes Called "implicit" or "automatic type conversion"
Literals
2, 5.75, "Z", "Hello World" Considered "constants": cant change in program
Lit l D t
-
8/8/2019 Computer Science stuff, chapter 1
38/104
381-38
Literal Data
Literals
Examples:
2 // Literal constant of int type 5.75 // Literal constant of double type
Z // Literal constant of char type
"Hello World" // Literal constant ofstring
type
Cannot change values during execution.
Called "literals" because you "literally typed"
them in your program!
E l
-
8/8/2019 Computer Science stuff, chapter 1
39/104
39
Examples
i = 0;
i = i + 1;
x = 10.5;
x = 2 * x - 1.75;
ch = B;
B
i x ch
01 10.500019.2500
ASCII
-
8/8/2019 Computer Science stuff, chapter 1
40/104
40
ASCII
Assignment Statement
-
8/8/2019 Computer Science stuff, chapter 1
41/104
41
Assignment Statement
The computations would take place in the ALU and theresulting values would be sent to and stored in the bytesof memory associate with the variables.
You should be careful to read such assignments,variable = value, as either "assign to the variable thevalue" or "set the variable to the value", e.g. the
statement i = i + 1; should be read as "assign to ithe value of i + 1" or "set i to the value of i + 1".
Do not read the symbol = as equal. It does not meanequal.
Constants
-
8/8/2019 Computer Science stuff, chapter 1
42/104
42
Constants
Naming your constants Literal constants are "OK", but provide
little meaning e.g., seeing 24 in a program, tells nothing about
what it represents
Use named constants instead Meaningful name to represent data
const int NUMBER_OF_STUDENTS = 24;
Called a "declared constant" or "named constant" Now use its name wherever needed in program
Added benefit: changes to value result in one fix
Example
-
8/8/2019 Computer Science stuff, chapter 1
43/104
43
Example
24
24
24
24
24
const intNUMBER_OF_STUDENTS=24;
NUMBER_OF_STUDENTS
NUMBER_OF_STUDENTS
NUMBER_OF_STUDENTS
NUMBER_OF_STUDENTS
NUMBER_OF_STUDENTS
Now change the number of students to 36.
Arithmetic Operators
-
8/8/2019 Computer Science stuff, chapter 1
44/104
44
Arithmetic Operators
The simple arithmetic operators that can beused for computing values are written in C as:
+ (add), - (subtract),
* (multiply),
/ (divide).
Simple Output
-
8/8/2019 Computer Science stuff, chapter 1
45/104
45
Simple Output
cout
-
8/8/2019 Computer Science stuff, chapter 1
46/104
46
Simple Output
The values to be outputted can be integers, doubles,chars, strings or any other C++ type of value.
One of the most common type value to be outputted is astring literal. A string literal is any sequence ofcharacters between double quotes, string-literal.
The values are outputted with no extra space aroundthem so often one outputs a string like between
each pair of values to cause a space to occur betweenthem.
Simple Output
-
8/8/2019 Computer Science stuff, chapter 1
47/104
47
Simple Output
The name cout stands for console output whereconsole refers to the combination of the keyboard andmonitor, i. e. the basic input/output devices.
More specifically cout is referred to as the consoleoutput stream object. We will explain this terminologylater in the course.
The symbol
-
8/8/2019 Computer Science stuff, chapter 1
48/104
48
Example
int i = 75;
double x = 2.5;
char ch = A;
cout
-
8/8/2019 Computer Science stuff, chapter 1
49/104
49
Output: Double
The output of double type values is somewhatproblematic. For examplex = 12345.6789;
cout
-
8/8/2019 Computer Science stuff, chapter 1
50/104
50
Output: Double
x = 123456789.0;
cout
-
8/8/2019 Computer Science stuff, chapter 1
51/104
51
Scientific Notation
08
02
1.23456 1.23456 *10 123456000
1.23456 1.23456 *10
08
02 0.0123456
e
e
=
+
= =
=
Output: Double
-
8/8/2019 Computer Science stuff, chapter 1
52/104
52
Output: Double
If you would like for doubles to always be outputtedusing fixed point notation and with a decimal point shownyou should place the following before the first such
output.cout.setf(ios::fixed );
cout.setf(ios::showpoint);
or more brieflycout.setf(ios::fixed | ios::showpoint);
This will guarantee that double numbers will be outputtedin fixed point notation and will always show a decimal
point. This notation will be explained in detail later.
Output: Precision
-
8/8/2019 Computer Science stuff, chapter 1
53/104
53
Output: Precision
If you would also like to guarantee that exactly ndigits to the right of the decimal point are shown
you can usecout.precision(n);
for example cout.precision(2); would show 2
digits to the right of the decimal point.
Example
-
8/8/2019 Computer Science stuff, chapter 1
54/104
54
Example
double x = 12345.6789, y = 123456789.0;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);cout
-
8/8/2019 Computer Science stuff, chapter 1
55/104
55
p p
cin>>variable-1>>>>variable-n;
This instruction will cause a value of the appropriate typeto be inputted from the keyboard into each of the n
variables. The name cin stands for console input where console
refers to the combination of the keyboard and monitor,
i.e. the basic input/output devices. The symbol >> is called the extraction operator
because it extracts values from the typed input at thekeyboard.
Simple Input
-
8/8/2019 Computer Science stuff, chapter 1
56/104
56
p p
The values to be inputted should be typed using thekeyboard and normally separated by one or more white-space characters where the space bar produces a space
character and the enter key produces a new-linecharacter that is also a white-space character.
An input value of type char does not have quote marks
around it like a character constant in C++ code does. When attempting to input a value of any type leadingwhite-space characters are skipped over.
This means that for a character variable the valueinputted will be the first non-white-space character.
Simple Input
-
8/8/2019 Computer Science stuff, chapter 1
57/104
57
p p
int i; double x; char ch;
cin>>i>>x>>ch;
If the user typed the following at the keyboard15 79.8 A
then the values input for the variables would bei=15, x=79.8, ch=A.
You would get the same result if extra spaces
were typed between the values or even if theenter key were typed between the values.
Example
-
8/8/2019 Computer Science stuff, chapter 1
58/104
58
p
int i; double x; char ch;
cin >> i >> x >> ch;
15 79.8 A
15 79.8 A
15 79 .8 A
15 79.8 A
15 79.8 A
15 79 .
Example
-
8/8/2019 Computer Science stuff, chapter 1
59/104
59
p
int i, x; char ch;
Cin >> i >> x >> ch;
15 79.8 A
15 79A
15 79 .8 A
15 79 .
15 79 A
15 79 .
Example
-
8/8/2019 Computer Science stuff, chapter 1
60/104
60
p
Various things can go wrong during input. For example
int i, x; char ch;
cin>>i>>x>>ch;
If the user typed the following at the keyboard
15 79.8 A
then the values inputted for the variables would be i=15,x=79, ch=..
This is because variable x in this example is of type intand thus the input attempts to get an integer value for x
and thus stops at 79 which is an integer. That means the next character in the input is . And
since this is a non-white-space character it is inputted for
ch.
Input
-
8/8/2019 Computer Science stuff, chapter 1
61/104
61
This also means that all the characters after .(i.e. 8 A\n) are still waiting in the input buffer to be usedthe next time input is attempted and this will probably
mess up the next input. Note that the character \n which is the so called new-line character is in the input because the user pressedthe enter key at the end of the typed input and that key
stroke puts this special character in the input buffer. The new-line character is an example of a special type ofcharacter that is represented by the two characters \ andn.
The back-slash character is the so called escapecharacter and is needed so that the computer escapesform the usual interpretation of n as a regular characterand instead gives it the meaning new-line.
Escape Sequences
-
8/8/2019 Computer Science stuff, chapter 1
62/104
621-62
"Extend" character set
Backslash, \ preceding a character
Instructs compiler: a special "escape character" iscoming
Following character treated as escape sequence
char"
Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Some Escape Sequences (1 of 2)
-
8/8/2019 Computer Science stuff, chapter 1
63/104
631-63Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Some Escape Sequences (2 of 2)
-
8/8/2019 Computer Science stuff, chapter 1
64/104
641-64Copyright 2008 Pearson Addison-Wesley. All rights reserved.
Input
-
8/8/2019 Computer Science stuff, chapter 1
65/104
65
Things can go even worse. Consider this example.
int i;
cin>>i;
If the user types
A5
then nothing will be input into i since the first non-white-space character A cannot be part of an integer value andthus there is no integer to input.
Failed State
-
8/8/2019 Computer Science stuff, chapter 1
66/104
66
In this case the input enters what is called a failed state.
If any further input is attempted in the program then noinput occurs, but the program execution continues as ifeverything was ok.
Later we will learn how to deal with failed input, but fornow we will simply assume the user always types correctinput and if s/he does not then the program results aremeaningless and the program must be re-run.
Read Head
-
8/8/2019 Computer Science stuff, chapter 1
67/104
67
1 5 7 9 . 8 A \n
15 79.8 A
Reading: int , double, char
Read Head
-
8/8/2019 Computer Science stuff, chapter 1
68/104
68
1 5 7 9 . 8 A \n
15
More detail in reading an int
1 5
Quiz
-
8/8/2019 Computer Science stuff, chapter 1
69/104
69
What is the double if the input stream is15 78x9 A?
What is the double if the input stream is15 78e9 A?
Read Head
-
8/8/2019 Computer Science stuff, chapter 1
70/104
70
1 5 7 9 . 8 A \n
15 79 .
Reading: int, int, char
Read Head
-
8/8/2019 Computer Science stuff, chapter 1
71/104
71
1 2 \n 3 4 5 \n
1 2 3
Reading: int, int, char
Read Head
-
8/8/2019 Computer Science stuff, chapter 1
72/104
72
1 2 \n 3 4 5 \n
4 5
Reading: int, int, char (again)
Rules
-
8/8/2019 Computer Science stuff, chapter 1
73/104
73
Skip leading blanks (and other whitecharacters),
In reading numbers, consume as many characters aspossible (legal integer or real number),
Greedy
In reading characters, consume only one.
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
74/104
74
This program
defines a constant cost of 1.50 per slice of pizza,
prompts the user for the number of slices of pizza acustomer has ordered,
computes the cost and outputs a bill for the customer.
Exam1-2.cpp
Example 1-2
http://../CPP/ch01/exam1-2.cpphttp://../CPP/ch01/exam1-2.cpp -
8/8/2019 Computer Science stuff, chapter 1
75/104
75
This program illustrates C++ I/O. It also illustrates theuse of a constant.const double PRICE_PER_SLICE = 1.50;
Constants in C++ are usually defined before the mainfunction.
The declaration of a constant is like a regular variable
declaration except that the word const precedes theusual variable declaration and a constant must beinitialized. (why?)
As its name suggests a constants value cannot be
changed. It is conventional (especially in C, but also inC++) to name constants in all upper case so they can beeasily distinguished from regular variables.
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
76/104
76
Note the first output instruction that prompts theuser to enter the number of slices of pizza does
not have an endl after it because we want toleave the cursor on the same line as theprompting message so the user can enter the
number of slices on the same line as shown inthe example I/O.
Enter number of slices desired: 3
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
77/104
77
Note that the rest of the output has one outputinstruction for each line of output. That is my
preferred style. However the rest of the outputcould have been done as follows with equal clarity.
cout
-
8/8/2019 Computer Science stuff, chapter 1
78/104
78
The preprocessor directive#include
is needed because the file stdlib or cstdlib containsinformation about the system function. Asmentioned in the appendix about using Dev-C++the instruction system(PAUSE) is one way to
make the I/O window to stay open so we cansee it. This is not a necessary part of C++, butjust necessary for certain C++ systems like Dev-C++ and Visual C++.
From now on I may not show this in programs,but you should use this in every Dev-C++program.
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
79/104
79
**********************************
Joe's Pizza Shack Bill
Number of Slices of Pizza = 10
Price per Slice = $1.50
Total Cost = $15.00
**********************************
This might look better if it were printed like the following instead.
**********************************
Joe's Pizza Shack Bill
Number of Slices of Pizza = 10
Price per Slice = $ 1.50
Total Cost = $15.00
**********************************
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
80/104
80
The computer use only minimum space to print out thenumber (four characters as in 1.50) unless otherwiseinstructed.
We can cause this to happen by telling the output to puteach of these 2 numbers in a field of width 5.
This is done by either cout.width(5) or by using the
manipulator setw(5).
In either case this width only applies for the next valueoutputted.
Example 1-2
-
8/8/2019 Computer Science stuff, chapter 1
81/104
81
It is easier to use the setw manipulator. To do so onemust include the header file for these I/O manipulators(#include ). Then one would write the output
instructions that output these 2 lines as
cout
-
8/8/2019 Computer Science stuff, chapter 1
82/104
82
Note the setw(5) manipulator is put in the outputinstruction like it was a value to be outputted.
However it does not cause an output, but insteaddetermines the field width for the next value that isoutputted.
Any time you want values to line up (align) in some way
when the sizes of the values may vary you can achievethis by setting the field width for each to some sizesufficient for the largest value.
Arithmetic Expressions
-
8/8/2019 Computer Science stuff, chapter 1
83/104
83
The arithmetic operators in C++ are
+ (add),
- (subtract),
* (multiply),
/ (divide),
% (remainder of an integer division)
Operators
-
8/8/2019 Computer Science stuff, chapter 1
84/104
84
The first 3 operators do not require any further comment.
The division operation is done differently depending onwhether both numbers it is being performed on are
integer or not.
If both are integers then the division is integer division and theresult is an integer computed by doing the division and
discarding the remainder. If either of the 2 numbers is a real number (double or float) then
the division is floating point division and the result contains thedigits after the decimal point to as great an accuracy as the
computer can store.
Operators
-
8/8/2019 Computer Science stuff, chapter 1
85/104
85
The operator % (the modulus operator) is only used withintegers and gives the remainder of an integer division.
Example:
10 % 6 = 4
10 % 5 = 0
10 % 4 = 2
10 % 3 = 1
10 % 2 = 0
Example
-
8/8/2019 Computer Science stuff, chapter 1
86/104
86
Example
7/2
7%2
14/3
14%3 7.0/2.0
14.0/3.0
7.0/2
14/3.0
3 (integer)
1 (integer)
4 (integer)
2 (integer)
3.50000000000000 (floating pt)
4.66666666666667 (floating pt)
3.50000000000000 (floating pt)
4.66666666666667 (floating pt)
Operator Precedence
Th d f l i f i i h i
-
8/8/2019 Computer Science stuff, chapter 1
87/104
87
The order of evaluation of operators in an arithmeticexpression is similar to the order learned inmathematics.
Technically it is determined by the precedence of theoperators where higher precedence operators areperformed before lower precedence operators. Theprecedence table for these operators is highest: ( )
sub-expression in parentheses are done before others
* / %if several operators of same precedence then done from left toright
lowest: + -if several operators of same precedence then done from left toright
Example
-
8/8/2019 Computer Science stuff, chapter 1
88/104
88
a * (b + c) / d - e % f
+
*
/
%
-
Example
If h d l
-
8/8/2019 Computer Science stuff, chapter 1
89/104
89
If we had valuesa=3; b=4; c=1; d=4; e=7; f=5;
then the value of the expression would be 3 * (4 + 1) / 4 - 7 % 5
3 * 5 / 4 - 7 % 5
15 / 4 - 7 % 5
3 - 7 % 5
3 - 2
1
Example
* b / (d % f)
-
8/8/2019 Computer Science stuff, chapter 1
90/104
90
a * b + c / (d - e % f)
3 5 4 2 1 order
3 * 4 + 1 / (4 - 7 % 5)
3 * 4 + 1 / (4 - 2 )
3 * 4 + 1 / 2 12 + 1 / 2
12 + 0
12
Example
3 0 * 4 1 / (4 7 % 5)
-
8/8/2019 Computer Science stuff, chapter 1
91/104
91
3.0 * 4 + 1 / (4 - 7 % 5) 3.0 * 4 + 1 / (4 - 2 ) 3.0 * 4 + 1 / 2
12.0 + 1 / 2 12.0 + 0 12.0
Note that the division was an integer divisionbecause both of its operands were integers. It is generally a bad idea to mix types in the
same expression although the results areusually as expected unless a division is involvedin which case you must think very carefullyabout the result.
Example
3 * 4 1 0 / (4 7 % 5)
-
8/8/2019 Computer Science stuff, chapter 1
92/104
92
3 * 4 + 1.0 / (4 - 7 % 5)
3 * 4 + 1.0 / (4 - 2 )
3 * 4 + 1.0 / 2 12 + 1.0 / 2
12 + 0.5
12.5
Operators
-
8/8/2019 Computer Science stuff, chapter 1
93/104
93
Integer
Floating Pt
Floating Pt
Floating Pt
Integer
IntegerOp Integer
Op
Op Floating Pt
Floating Pt
Floating Pt
Notes
If you write arithmetic expressions in C++ in the way that
-
8/8/2019 Computer Science stuff, chapter 1
94/104
94
If you write arithmetic expressions in C++ in the way thatfeels correct based on your experience withmathematical expressions and put in extra parentheses
when you are not sure then you will generally get thecorrect result.
x * b + c / (d - e % f)
(x * b) + (c / (d (e % f)))
Redundant but correct.
Automatic Conversion
As a final point consider what happens when a value of
-
8/8/2019 Computer Science stuff, chapter 1
95/104
95
As a final point consider what happens when a value ofone type is assigned to a variable of a different type. When an integer is assigned to a double variable the integer is
converted to a double and there is generally no loss of accuracy.
However when a double is assigned to an integer variable thenthe number is converted to an integer by truncating the digitsafter the decimal point with a loss of accuracy.
Also since the range of numbers for doubles is muchgreater than for integers the resulting integer may be toolarge to be stored properly in the memory allocated forthe integer.
This may result in an error called integer overflow andresult in very odd results for the value of the integervariable.
Automatic Conversion
For example suppose we have int i; double x; and do the
-
8/8/2019 Computer Science stuff, chapter 1
96/104
96
For example suppose we have int i; double x; and do thefollowing assignments.
x = 2; 2 will be converted to 2.0 and assigned to x.
i = 2.9; 2.9 will be converted to 2 and assigned to i.
Very large double values can be written in C++ in a formsimilar to scientific notation.
For example 2.9e50 is C++'s way of writing the number2.9 times 10 to the power of 50. If we try to assign sucha large number to an integer variable then an error in the
value is sure to result.
Automatic Conversion
i = 2 9E50; 2 9E50 will be converted to an integer
-
8/8/2019 Computer Science stuff, chapter 1
97/104
97
i = 2.9E50; 2.9E50 will be converted to an integertoo large to be stored, resulting in an integer overflowand some very odd value assigned to i.
Integer
Floating Pt Integer
Floating Pt
?
Type Casting
static cast(value) casts the value as type
-
8/8/2019 Computer Science stuff, chapter 1
98/104
98
static_cast(value) casts the value as type Sometimes one has 2 integer values and one wants to
do a floating point division. One way to force this is to
cast one or both on the integers as doubles. For example suppose we had
int num, sum;
double average;
and num = 3 and sum = 8 and we wanted to compute theaverage as sum/num. If we do the instruction average =sum/num; we would get 2.0 assigned to average since 8
/ 3 is 2. To get a floating point division we must makeat least one of the numbers into a double average = static_cast(sum) / num;
Casting
This casts the value of sum as a double and thus results
-
8/8/2019 Computer Science stuff, chapter 1
99/104
99
This casts the value of sum as a double and thus resultsin a floating point division.
It does not change the value or type of the variable sum
it just changes this value (in the ALU) while the divisionis being done.
Another form for writing this cast in C that is still allowedin C++ is (double)sum instead ofstatic_cast(sum).
You can use a cast to change a value to other typesalso, but this by far the most common use of a cast.
There are also some other types of casts that we will notuse in this class.
Increment/Decrement Operators
C++ has 2 operators called the increment
-
8/8/2019 Computer Science stuff, chapter 1
100/104
100
C++ has 2 operators called the incrementoperator and the decrement operator. ++v increments v, i.e. has the effect of
v = v + 1 and returns the incremented value. v++ also increments v, i.e. has the effect ofv = v + 1, but returns the original value.
--v decrements v, i.e. has the effect ofv = v 1 and returns the decremented value.
v-- also decrements v, i.e. has the effect ofv = v 1, but returns the original value.
These operators can be applied to variablesonly, not to expressions.
Increment/Decrement Operators
If these operators are used as part of a larger expression
-
8/8/2019 Computer Science stuff, chapter 1
101/104
101
If these operators are used as part of a larger expressionthen it matters whether you use the pre (++v, --v) or post(v++, v--) forms, but when standing alone they have
exactly the same effect of either incrementing ordecrementing the variable.
When used as part of another expression the pre form
does the increment or decrement before the value isused in the expression while the post form does theincrement or decrement after the value is used.
Read v++ as return the value v and then increment it, Read ++v as increment v and then return the value.
Example
k = 7; k = 7;
-
8/8/2019 Computer Science stuff, chapter 1
102/104
102
k 7;
i = 0;
k = ++i;
k 7;
i = 0;
k = i++;
0
7
i
k
0
7
i
k -- 0
-- 1-- 1
-- 1
Increment/Decrement Operators
When used in larger expressions their meaning can bediffi lt t d t d
-
8/8/2019 Computer Science stuff, chapter 1
103/104
103
g p gdifficult to understand.
Recommendation for beginners: I will only use themstanding alone and I suggest you do the same.
Used alone both ++v and v++ are the same asv = v + 1 and both --v and v-- are the same asv = v 1.
Incidentally the name of the language C++ comes fromthe post-increment operator. The inventor of thelanguage thought this was a clever way of saying C++ isC incremented (with many new features).
Example
See example 1-3.
-
8/8/2019 Computer Science stuff, chapter 1
104/104
104
See example 1 3.
The casting could also be done by avg3 = (double)sum / num;
What is the difference between the twocastings?
avg3 = static_cast(sum) / num ; avg4 = static_cast(sum / num);
Example 1-3, 1-3a, 1-3b.cpp
http://../CPP/ch01/exam1-3.cpphttp://../CPP/ch01/exam1-3a.cpphttp://../CPP/ch01/exam1-3b.cpphttp://../CPP/ch01/exam1-3b.cpphttp://../CPP/ch01/exam1-3a.cpphttp://../CPP/ch01/exam1-3.cpp