diff --git a/.gitignore b/.gitignore
index b3bfa9c..27f2579 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,9 @@
# ensure this file is tracked
!.gitignore
+# don't track the .cache directory
+.cache/*
+
# don't track unpublished builds or stage
output
diff --git a/README.rst b/README.rst
index f40c9a1..f41d20d 100644
--- a/README.rst
+++ b/README.rst
@@ -10,7 +10,7 @@ College students in 2018 and early 2019. Other portions of this book began as
web pages written by Jan Pearce as support for a Berea College C++ programming class.
Still other sections were newly written by Jan Pearce for this ebook.
-Special acknowledgement is due to `Jesse Walker-Schadler `_ who while just a student in the Berea College Data Structures course had a vision of making graphics in C++ as easy as they are in Python both in terms of both syntax and installations. Over the course of two summers, he realized this vision with the creation in `the open source CTurtle library `_ which provides all of the C++ interactive graphics in this textbook.
+Special acknowledgement is due to `Jesse Walker-Schadler `_ who while just a student in the Berea College Data Structures course had a vision of making graphics in C++ as easy as they are in Python both in terms of both syntax and installations. Over the course of two summers, he realized this vision with the creation in `the open source CTurtle library `_ which provides all of the C++ interactive graphics in this textbook.
How to use and suggest changes to this book
===========================================
diff --git a/_sources/AtomicData/Figures/new_new_point2.png b/_sources/AtomicData/Figures/new_new_point2.png
index fe232f1..7bb3e92 100644
Binary files a/_sources/AtomicData/Figures/new_new_point2.png and b/_sources/AtomicData/Figures/new_new_point2.png differ
diff --git a/old-project.ptx b/old-project.ptx
new file mode 100644
index 0000000..d96d920
--- /dev/null
+++ b/old-project.ptx
@@ -0,0 +1,64 @@
+
+
+
+
+
+ html
+ pretext/cpp4python.ptx
+ pretext/publication-rs-for-all.xml
+ output/html
+
+
+ html
+ pretext/cpp4python.ptx
+ pretext/publication-rs-academy.xml
+ published/cpp4py-v2
+
+
+ epub
+ pretext/cpp4python.ptx
+ pretext/publication-pub.xml
+ published/epub
+
+
+ latex
+ pretext/cpp4python.ptx
+ pretext/publication-rs-for-all.xml
+ output/latex
+
+
+ pdf
+ pretext/cpp4python.ptx
+ pretext/publication-rs-for-all.xml
+ output/pdf
+
+
+ html
+ source/cpp4python.ptx
+ publication/publication.ptx
+ output/subset
+
+
+ ch-first
+
+
+
+ latex
+ pdflatex
+ xelatex
+ pdf2svg
+ asy
+ sage
+ convert
+ pdftops
+ pdf-crop-margins
+ pageres
+ node
+ file2brl
+
+
diff --git a/pretext/AtomicData/BooleanData.ptx b/pretext/AtomicData/BooleanData.ptx
index ace26ff..b4ac624 100644
--- a/pretext/AtomicData/BooleanData.ptx
+++ b/pretext/AtomicData/BooleanData.ptx
@@ -1,8 +1,8 @@
Boolean Data
-
Boolean data types are named after George Boole who was an English mathematician,
+
Boolean Boolean data types are named after George Boole who was an English mathematician,
so the word Boolean should be capitalized. However,
- the Boolean data type, in C++ uses the keyword bool
+ the Boolean data type, in C++ uses the keyword bool bool
which is not capitalized.
The possible state values
for a C++ Boolean are lower case true and false.
@@ -10,14 +10,14 @@
In Python, these same truth values are capitalized, while in C++,
they are lower case.
C++ uses the standard Boolean operators, but they are represented
- differently than in Python: and is given by && , or is given by ||
+ differently than in Python: and is given by && && , or is given by || ||
, and not is given by !.
Note that the internally stored values representing true and false
are actually 1 and 0 respectively. Hence, we see this in output as well.
-
+
#include <iostream>
using namespace std;
@@ -29,12 +29,12 @@ int main() {
cout << (true && false) << endl;
return 0;
}
-
+
-
+
# Function that demonstrates logical operators.
def main():
print(True)
@@ -42,11 +42,11 @@ def main():
print(True or False)
print(True and False)
main()
-
+
Boolean data objects are also used as results for comparison operators
- such as equality (==) and greater than (>). In addition,
+ such as equality (==) == and greater than (>) > . In addition,
relational operators and logical operators can be combined together to
form complex logical questions. shows the relational
and logical operators with examples shown in the session that follows.
@@ -176,7 +176,7 @@ main()
-
+
#include <iostream>
using namespace std;
@@ -189,12 +189,12 @@ int main(){
return 0;
}
-
+
-
+
# Function that demonstrates relational operators.
def main():
@@ -203,7 +203,7 @@ def main():
print((5 >= 1) and (5 <= 10))
main()
-
+
When a C++ variable is declared, space in memory is set aside to hold
@@ -213,7 +213,7 @@ main()
Consider the following session:
-
+
#include <iostream>
using namespace std;
@@ -236,7 +236,7 @@ int main(){
return 0;
}
-
+
The declaration int theSum = 4; creates a variable called
theSum and initializes it to hold the data value of 4git.
@@ -298,8 +298,53 @@ int main(){
-
-
-
+
+
+
+ Rearrange the blocks to create a C++ function checkCondition that takes two integers, score and lives. It should return a bool value indicating if score is greater than or equal to 100ANDlives is strictly greater than 0.
+
In Python strings can be created with single or double quotes.
- In C++ single quotes are used for the character (char) data type,
+ In C++ single quotes are used for the character (char) char data type,
and double quotes are used for the string data type.
Consider the following code.
-
+
# Shows direct comparison of both Strings & Characters in Python
def main():
@@ -19,12 +19,12 @@ def main():
print('a' == "a")
main()
-
+
-
+
#include <iostream>
#include <string>
using namespace std;
@@ -42,7 +42,7 @@ int main(){
return 0;
}
-
+
Try the following question.
diff --git a/pretext/AtomicData/CharactersData.ptx b/pretext/AtomicData/CharactersData.ptx
index d0155e6..fe674c6 100644
--- a/pretext/AtomicData/CharactersData.ptx
+++ b/pretext/AtomicData/CharactersData.ptx
@@ -4,10 +4,10 @@
In C++ single quotes are used for the character (char) data type,
and double quotes are used for the string data type.
Consider the following code.
-
+
-
+
# Shows direct comparison of both Strings & Characters in Python
def main():
@@ -19,12 +19,12 @@ def main():
print('a' == "a")
main()
-
+
-
+
#include <iostream>
#include <string>
using namespace std;
@@ -42,7 +42,7 @@ int main(){
return 0;
}
-
+
Try the following question.
diff --git a/pretext/AtomicData/NumericData.ptx b/pretext/AtomicData/NumericData.ptx
index 2874d6a..fcf70f0 100644
--- a/pretext/AtomicData/NumericData.ptx
+++ b/pretext/AtomicData/NumericData.ptx
@@ -1,7 +1,7 @@
Numeric Data
-
Numeric C++ data types include int for integer, float
- for floating point, double for double precision floating point.
+
Numeric C++ data types include int int for integer, float float
+ for floating point, double double for double precision floating point.
The standard arithmetic operations, +, -, *, and /
are used with optional parentheses to force the order of
operations away from normal operator precedence.
@@ -12,13 +12,13 @@
i.e. When two integers are divided, integer division is used.
To get the whole quotient, declaring one of the numbers as a float will
convert the entire result into floating point.
-
Exponentiation in C++ is done using pow() from the cmath library
- and the remainder (modulo) operator is done with %.
+
Exponentiation in C++ is done using pow() pow() from the cmath cmath library
+ and the remainder (modulo) operator is done with % % .
Run the following code to see that you understand each result.
-
+
#include <iostream>
#include <cmath>
using namespace std;
@@ -40,12 +40,12 @@ int main(){
return 0;
}
-
+
-
+
# Function that performs a variety of math operations.
def main():
@@ -62,7 +62,7 @@ def main():
print(2**100)
main()
-
+
When declaring numeric variables in C++,
diff --git a/pretext/AtomicData/Pointers.ptx b/pretext/AtomicData/Pointers.ptx
index 5e5cb22..75cb472 100644
--- a/pretext/AtomicData/Pointers.ptx
+++ b/pretext/AtomicData/Pointers.ptx
@@ -1,6 +1,6 @@
Pointers
-
A C++ pointer is a variable that stores a memory address and can be used to indirectly
+
A C++ pointerpointeris a variable that stores a memory address memory address and can be used to indirectly
access data stored at that memory location.
We know that variables in a computer program are used to label data with a
descriptive identifier so that the data can be accessed and used by that
@@ -36,11 +36,11 @@ int varN = 100;
it is sometimes a hexadecimal code and sometimes just a count or another
way to reference the address.
In Python we use id to reference the address,
- while in C++ we use the address-of operator, &.
+ while in C++ we use the address-of operatoraddress-of operator, &.
-
+
#include <iostream>
using namespace std;
@@ -53,12 +53,12 @@ int main(){
cout << &varN << endl; //outputs the memory address of variable varN
return 0;
}
-
+
-
+
# Outputs the value & memory address of
# variable titled varN.
def main():
@@ -67,7 +67,7 @@ def main():
print(id(varN)) # ID function returns the memory address in Python.
main()
-
+
In both Python and C++, variables are stored in memory locations which are dependent
@@ -89,7 +89,7 @@ main()
identifier.
variableType *identifier; // syntax to declare a C++ pointer
int *ptrx; // example of a C++ pointer to an integer
-
White space in C++ generally does not matter, so the following pointer declarations
+
White space in C++ generally does not matter, so the following pointer declarations pointer declarations
are identical:
Now that we know how to declare pointers, how do we give them the address of
where the value is going to be stored? One way to do this is to have a pointer
refer to another variable by using the address-of operator, which is denoted by the
- ampersand symbol, &. The address-of operator & does exactly what it indicates,
+ ampersand symbol, & & . The address-of operator & does exactly what it indicates,
variableType varN; // a variable to hold the value
namely it returns the address.
The syntax is shown below, where varN stores the value, and ptrN stores
@@ -123,7 +123,7 @@ ptrN = &varN;
Accessing Values from Pointers
Once you have a C++ pointer, you use the asterisk before the pointer variable,
- to dereference the pointer, which means go to the location pointed at by the 3.
+ to dereferencedereferencethe pointer, which means go to the location pointed at by the 3.
In other words, varN and *ptrN (note the asterisk in front!) reference the same
value in the code above.
Let's extend the example above to output the value of a variable and its address
@@ -132,7 +132,7 @@ value in the code above.
-
+
#include <iostream>
using namespace std;
@@ -148,7 +148,7 @@ int main( ) {
return 0;
}
-
+
@@ -167,7 +167,7 @@ int main( ) {
-
+
#include <iostream>
using namespace std;
@@ -185,7 +185,7 @@ int main( ) {
return 0;
}
-
+
This is BAD, BAD, BAD!
@@ -200,42 +200,42 @@ int main( ) {
(1) You don't know what is stored in location 100 in memory, and
(2) that location is outside of your segment (area in memory reserved
for your program), so the operating system will jump in with a message
- about a segmentation fault. Although such an error message looks bad,
+ about a segmentation faultsegmentation fault. Although such an error message looks bad,
a seg fault is in fact a helpful error because unlike the elusive logical
errors, the reason is fairly localized.
The null pointer
-
Like None in Python, the null pointer (nullptr) in C++ points to
+
Like None in Python, the null pointer null pointer (nullptr) in C++ points to
nothing. Older editions of C++ also used NULL (all caps) or 0,
but we will use the keyword nullptr because the compiler can do
better error handling with the keyword. The null pointer is often used
in conditions and/or in logical operations.
The following example demonstrates how the null pointer works.
- The variable ptrx initially has the address of x when it is declared.
+ The variable pntrN initially has the address of varN when it is declared.
On the first iteration of the loop, it is assigned the value of
nullptr, which evaluates to a false value; thereby ending the loop:
-
+
#include <iostream>
using namespace std;
//Shows the use of a Null pointer to represent "nothing".
int main( ) {
- int x = 12345;
- int *ptrx = &x;
+ int varN = 100;
+ int *pntrN = &varN;
- while (ptrx) {
- cout << "Pointer ptrx points to " << &ptrx << endl;
- ptrx = nullptr;
+ while (pntrN) {
+ cout << "Pointer pntrN points to " << &pntrN << endl;
+ pntrN = nullptr;
}
- cout << "Pointer ptrx points to nothing!\n";
+ cout << "Pointer pntrN points to nothing!\n";
}
-
+
Helpful Tip: The null pointer becomes very useful when you must test
@@ -249,14 +249,14 @@ int main( ) {
-
If the lines (varN = 50;) and (cout << *ptrN << endl;) were inserted into line 7-8, what would it cout?
+
If the lines (varN = 50;) and (cout << "ptrN: " << *ptrN << endl;) were inserted between lines 7 and 8, what would it cout?
-
varPntr: 9
+
pntrN: 100
Not quite, the variable varN no longer equals 100 past line 7!
Drag each glossary term to its' corresponding definition. (Note: none of the data types are in this matching, but they are in the glossary)
Feedback shows incorrect matches.
- address-of(&) is used to access the memory address of a C++ variable.atomic data type Data type that cannot be broken down into any simpler data elements.dereferenceReads data in a pointers memory location.pointerVariables that store and manipulate memory addresses.
+ address-of(&) is used to access the memory address of a C++ variable.atomic data type Data type that cannot be broken down into any simpler data elements.dereferenceReads data in a pointers memory location.pointerVariables that store and manipulate memory addresses.
What is an Array?
An array is a data structure consisting of an ordered collection of data elements,
of identical type in which each element can be identified by an array index.
More technically, an array data structure is an ordered arrangement of values
located at equally spaced addresses in contiguous computer memory.
-
NOTE: A C++ array is always stored in contiguous memory. C++ arrays can be allocated in two different ways:
+
NOTE: A C++ arrayarray is always stored in contiguous memory. C++ arrays can be allocated in two different ways:
-
+
-
statically allocated in which the array size is fixed at compile-time and cannot change
+
statically allocated in which the array size is fixed at compile-time and cannot change
-
dynamically allocated in which pointers are used in the allocation process so the size can change at run-time
+
dynamically allocateddynamically allocatedin which pointers are used in the allocation process so the size can change at run-time
-
In modern C++, the statically allocated array is typically used
+
In modern C++, the statically allocated array statically allocated array is typically used
in situations when speed is essential or where hardware constraints exist, and a data structure
- called a vector is typically used when more flexibility is required.
+ called a vector vector is typically used when more flexibility is required.
As a Python programmer, you might see the array as the ancestor
of the Python list, and you might remember that Python lists are actually implemented via
an underlying array consisting of references.
@@ -29,16 +29,16 @@
of memory locations that we can then manipulate as a single
entity, and that at the same time gives us direct access to each
individual component.
-
Why use an Array?
+
Why use an Array?
C++ is a language often used for real-time or low-level processing
where speed is essential and/or there is only a fixed amount of space
available.
The fact that array elements are stored in memory in contiguous
- memory locations making look-up via index very, very fast.
- In computing, a word is the unit of data used by a particular processor design,
+ memory contiguous memory locations making look-up via index very, very fast.
+ In computing, a wordword is the unit of data used by a particular processor design,
such as 32 or 64 bits. For example, an array of 100 integer variables, with indices 0 through 99,
- might be stored as 100 words at memory addresses 20000, 20004, 20008, … 20396.
- The element with index i would be located at the address 20000 + 4 × i.
+ might be stored as 100 words at memory addresses 20000, 20004, 20008, 20396.
+ The element with index i would be located at the address 20000 + 4 * i.
Statically allocated C++ arrays must be declared with both a type and a size at compile-time.
double darray[4];
int iarray[10];
@@ -52,9 +52,9 @@ string arr3[] = {"this", "is", "an", "array"}; // This is size 4.
so the following are not the same.
double darray[] = {1.2}; // must use index to access value
double ddouble = 1.2; // cannot use index to access value
-
Be Cautious with Arrays
+
Be Cautious with Arrays
The speed and low-level control that arrays offer us
- as programmers is powerful… and dangerous.
+ as programmers is powerful and dangerous.
As a Python programmer, using a C++ array will
help you better understand the trade-offs of the
protections Python offers.
@@ -62,7 +62,7 @@ double ddouble = 1.2; // cannot use index to access value
-
+
// outputs all elements in the array
//to the console
#include <iostream>
@@ -75,12 +75,12 @@ int main(){
}
return 0;
}
-
+
-
+
"""Demonstrates how python protects from
iterating past the end of a list"""
@@ -90,7 +90,7 @@ def main():
print(mylist[i])
main()
-
+
The protections Python offers, however, takes time and C++ is designed for speed.
@@ -105,7 +105,7 @@ main()
-
+
#include <iostream>
using namespace std;
@@ -120,12 +120,12 @@ int main(){
}
return 0;
}
-
+
-
+
"""Demonstrates how python protects from
iterating past the end of a list,
and shows the use of Id as the location in memory"""
@@ -137,7 +137,7 @@ def main():
print("id: "+str(id(mylist[i])))
main()
-
+
The speed of C++ comes at the cost of minimal to no error checking.
@@ -145,11 +145,11 @@ main()
You should use an array when you have a need for speed
or you need to work with hardware constraints.
Otherwise, you may want to consider using another collection data type,
- the vector.
+ the vector.
-
+
#include <iostream>
using namespace std;
@@ -173,12 +173,12 @@ int main(){
return 0;
}
-
+
-
+
"""Demonstrates how python protects from
iterating past the end of a list
and changing any other data"""
@@ -194,7 +194,7 @@ def main():
print("id: "+str(id(otherdata[i])))
main()
-
+
diff --git a/pretext/CollectionData/Collection.ptx b/pretext/CollectionData/Collection.ptx
index 8d55051..81eea87 100644
--- a/pretext/CollectionData/Collection.ptx
+++ b/pretext/CollectionData/Collection.ptx
@@ -2,7 +2,7 @@
Collections
In addition to the numeric, Boolean, and character types,
C++ also offers built-in collection types.
- A collection data type is a grouping of some number of other data items
+ A collectioncollection data type is a grouping of some number of other data items
(possibly only zero or one) that have some shared significance
or need to be operated upon together.
Arrays, vectors, strings, sets, and hash tables are among these useful
diff --git a/pretext/CollectionData/HashTables.ptx b/pretext/CollectionData/HashTables.ptx
index cde7937..87a1a90 100644
--- a/pretext/CollectionData/HashTables.ptx
+++ b/pretext/CollectionData/HashTables.ptx
@@ -1,18 +1,18 @@
Hash Tables
If you have used a Python dictionary, then you have used a hash table.
- A hash table is a collection of associated pairs of
- items where each pair consists of a key and a value.
- Hash tables are often called the more general term map
+ A hash tablehash table is a collection of associated pairs of
+ items where each pair consists of a key and a value.
+ Hash tables are often called the more general term map
because the associated hash function maps the key to the value.
- Nevertheless, it is better to use the more precise term, hash table
+ Nevertheless, it is better to use the more precise term, hash table
because other kinds of maps are sometimes implemented with a different underlying data structure.
-
Each hash table has a hash function which
+
Each hash table has a hash functionhash function which
given the key as input to the hash function
returns the location of the associated value as the output.
This makes look up fast.
In Python, the dictionary data type represents the implementation of the hash table.
- In C++, the unordered_map implements the hash table, and the <unordered_map>
+ In C++, the unordered_mapunordered_map implements the hash table, and the <unordered_map>
library must be included as follows:
#include <unordered_map>
The syntax for hash table access is much like we might expect
@@ -24,9 +24,9 @@
-
-// Creates a hash table that maches
-// the english letter to it's spanish
+
+// Creates a hash table that matches
+// the English letter to its Spanish
// equivalent, and outputs the size of
// the table to the console
#include <iostream>
@@ -47,12 +47,12 @@ int main() {
cout << spnumbers.size() << endl;
}
-
+
-
+
"""Python equivalent
of the C++ code """
def main():
@@ -66,7 +66,7 @@ def main():
print(len(spnumbers))
main()
-
+
It is important to note that hash tables are organized by the location given
@@ -81,9 +81,9 @@ main()
-
-// Creates a hash table that maches
-// the english letter to it's spanish
+
+// Creates a hash table that matches
+// the English letter to its Spanish
// equivalent, and outputs every item
// in the table to the console
#include <iostream>
@@ -105,12 +105,12 @@ int main() {
cout << i->second << endl;
}
}
-
+
-
+
"""Python equivalent
of the C++ code """
def main():
@@ -121,7 +121,7 @@ def main():
print(spnumbers[key])
main()
-
+
Hash Tables have both methods and operators.
@@ -217,6 +217,5 @@ main()
Match the Hash Table operations with their corresponding explination.
Feedback shows incorrect matches.
-[ ]Returns the value associated with the key, otherwise throws error.eraseDeletes the entry from the hash table.countReturns true if key is in the hash table, and false otherwise.beginAn iterator to the first element in the hash table.endAn iterator pointing to past-the-end element of the hash table.
-
-
+[ ]Returns the value associated with the key, otherwise throws error.eraseDeletes the entry from the hash table.countReturns true if key is in the hash table, and false otherwise.beginAn iterator to the first element in the hash table.endAn iterator pointing to past-the-end element of the hash table.
+
\ No newline at end of file
diff --git a/pretext/CollectionData/Strings.ptx b/pretext/CollectionData/Strings.ptx
index 6a09db2..9cf7c54 100644
--- a/pretext/CollectionData/Strings.ptx
+++ b/pretext/CollectionData/Strings.ptx
@@ -1,9 +1,9 @@
Strings
-
Strings are sequential collections of zero or more characters such as letters, numbers
- and other symbols. There are actually two types of strings in C++ . The C++ string or just string from the
+
Stringsstringsare sequential collections of zero or more characters such as letters, numbers
+ and other symbols. There are actually two types of strings in C++ . The C++ string or just string from the
<string> library is the more modern type, and it is very similar to the Python string class.
- The old style C-string which is essentially
+ The old style C-string which is essentially
an array of char type. The char type itself is actually distinct from both types of strings.
char cppchar = 'a'; // char values use single quotes
string cppstring = "Hello World!"; // C++ strings use double quotes
@@ -14,7 +14,7 @@ char cstring[] = {"Hello World!"}; // C-string or char array uses double quot
Because strings are sequences, all of the typical sequence operations work as you would expect.
- In addition, the string library offers a huge number of
+ In addition, the string library string library offers a huge number of
methods, some of the most useful of which are shown in .
@@ -155,7 +155,7 @@ char cstring[] = {"Hello World!"}; // C-string or char array uses double quot
-
+
// This function concatenates the string hello World
// Then it says where World begins in the concatenated string
#include <iostream>
@@ -176,12 +176,12 @@ int main(){
return 0;
}
-
+
-
+
"""This does the same thing as the C++ function """
def main():
mystring1 = "Hello"
@@ -195,7 +195,7 @@ def main():
print(str(mystring3.find(mystring2)))
main()
-
+
Check your understanding by completing the following question.
@@ -253,13 +253,13 @@ main()
Match the String operations with their corresponding explanation.
Feedback shows incorrect matches.
- [ ]Accesses value of an element.find Returns the index of the first occurrence of item.= Assigns value to an element.push_backAdjoins a character to the end of the string.pop_backRemoves the last character from the end of the string.
+ [ ]Accesses value of an element.find Returns the index of the first occurrence of item.= Assigns value to an element.push_backAdjoins a character to the end of the string.pop_backRemoves the last character from the end of the string.
Match the String operation with their corresponding explanation.
Feedback shows incorrect matches.
-
- insertInjects a string at a specific index.eraseDeletes an element from one index to another.sizeReturns the capacity of the string.+Connects strings.appendAdjoins a string to the end of the string.
-
+
+ insertInjects a string at a specific index.eraseDeletes an element from one index to another.sizeReturns the capacity of the string.+Connects strings.appendAdjoins a string to the end of the string.
+
@@ -268,7 +268,7 @@ main()
Drag each data type to its' corresponding C++ initialization syntax.
An unordered_set is an unordered collection of zero or more unique C++ data values
+
An unordered_setunordered_set is an unordered collection of zero or more unique C++ data values
of a particular type.
To use unordered_sets, you import unordered_set from the Standard template library with
- #include <unorderd_set>.
+ #include <unordered_set>.
Unordered_sets allow for fast retrieval of individual elements based on their value.
In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely.
Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container -
@@ -11,7 +11,7 @@
Unordered sets do not allow duplicates and are initialized using comma-delimited
values enclosed in curly braces. The collection can be assigned to
a variable as shown below.
-
set<int> mySet = {3, 6, 4, 78, 10}
+
unordered_set<int> mySet = {3, 6, 4, 78, 10};
Unordered sets support a number of methods that should be familiar to those who
have worked with sets in a mathematics setting.
provides a summary. Examples of their use follow.
@@ -118,9 +118,9 @@
The code below is an example of a program that can detect if a specific char is in an unordered set.
-
+
// Function that checks to see if a char
-// is in the unorderd set
+// is in the unordered set
#include <iostream>
#include <unordered_set>
using namespace std;
@@ -143,7 +143,7 @@ charSet.insert('e');
checker(charSet, letter);
return 0;
}
-
+
the find method used for a conditional in Checker compares
each item in the set with the given parameter until there is a match. the
@@ -159,6 +159,6 @@ return 0;
Match the Unordered Sets operations with their corresponding explination.
Feedback shows incorrect matches.
-unionReturns a new set with all elements from both sets.intersectionReturns a new set with only those elements common to both sets.difference Returns a new set with all items from first set not in second.addAdds item to the set.removeerases item from the set.clearRemoves all elements from the set.
+unionReturns a new set with all elements from both sets.intersectionReturns a new set with only those elements common to both sets.difference Returns a new set with all items from first set not in second.addAdds item to the set.removeerases item from the set.clearRemoves all elements from the set.
A very common programming task is to grow a vector using the push_back() method to append to the vector
as we see in the next example.
Because vectors can change size, vectors typically allocate some extra storage to accommodate for possible growth.
- Thus the vector typically has an actual capacity greater than the storage size strictly needed to contain its elements.
+ Thus the vector typically has an actual capacity greater than the storage size strictly needed to contain its elements.
Iterating through Vectors
When iterating vectors, you must first find the length of your container. You can simply call the .length() function.
@@ -151,7 +151,7 @@
of elements the Array contains!
-
+
#include <iostream>
using namespace std;
@@ -175,7 +175,7 @@ int main() {
return 0;
}
-
+
An optional secondary version of the for loop has been commented out of the above code.
You can try running this in your version of C++ to see if it works, but in some older versions of C++,
@@ -191,7 +191,7 @@ int main() {
-
+
// function that uses a vector to square
// every number from 0 to 49
// uses the reserve operation to save space in memory
@@ -210,12 +210,12 @@ int main(){
}
return 0;
}
-
+
-
+
"""Uses a list to square every
number from 0 to 49 """
def main():
@@ -225,7 +225,7 @@ def main():
print(intlist[i])
main()
-
+
In the above example, the use of reserve was optional. However, it is a good
@@ -237,7 +237,7 @@ main()
example that follows.
-
+
// function that uses a vector to square
// every number from 0 to 49
// and does not use reserve.
@@ -258,14 +258,14 @@ int main(){
}
return 0;
}
-
+
Remembering that C++ is designed for speed, not protection,
we will likely not be surprised by the following:
-
+
// Note: counting always starts at 0
// This demonstrates what happens when
// accessing datat outside of your vector
@@ -290,12 +290,12 @@ int main(){
return 0;
}
-
+
-
+
"""Demonstrates python's protections
against iterating outside of a list"""
def main():
@@ -307,7 +307,7 @@ def main():
print("intlist[" + str(i) + "]=" + str(intlist[i]))
main()
-
+
@@ -317,13 +317,13 @@ main()
Match the Vector operations with their corresponding explination.
Feedback shows incorrect matches.
- [ ]Accesses value of an element.= Assigns value to an element.push_backAppends item to the end of the vector.pop_back Deletes last item of the vector.insertInjects an item into the vector.
+ [ ]Accesses value of an element.= Assigns value to an element.push_backAppends item to the end of the vector.pop_back Deletes last item of the vector.insertInjects an item into the vector.
Match the Vector operations with their corresponding explination.
Feedback shows incorrect matches.
-
- eraseDeletes an element from the choosen index.sizeReturns the actual capacity used by elements.capacityReturns the ammount of allocated storage space.reserve Request a change in space to amount
-
+
+ eraseDeletes an element from the choosen index.sizeReturns the actual capacity used by elements.capacityReturns the ammount of allocated storage space.reserve Request a change in space to amount
+
diff --git a/pretext/CollectionData/summary.ptx b/pretext/CollectionData/summary.ptx
index 53e12a1..da3b7ed 100644
--- a/pretext/CollectionData/summary.ptx
+++ b/pretext/CollectionData/summary.ptx
@@ -1,6 +1,6 @@
Summary and Reading Questions
-
+
A statically allocated C++ array is an ordered collection of one or more C++ data values of identical type stored in contiguous memory.
@@ -87,25 +87,25 @@
Drag each data type to its' corresponding C++ initialization syntax.
Match the words to thier corresponding definition.
Feedback shows incorrect matches.
- stringA sequential data structure consisting of zero or more characters.collection a grouping of a number of data items that have some shared significance or need to be operated upon together.vectorsequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.hash tablea collection consisting of key-value pairs with an associated function that maps the key to the associated value.
+ stringA sequential data structure consisting of zero or more characters.collection a grouping of a number of data items that have some shared significance or need to be operated upon together.vectorsequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.hash tablea collection consisting of key-value pairs with an associated function that maps the key to the associated value.
Match the words to thier corresponding definition.
Feedback shows incorrect matches.
-
- arraya data structure consisting of an ordered collection of data elements of identical type in which each element can be identified by an index.
- wordunit of data used by a particular processor design.mutabilityable to be modified.immutableunable to be modified.
- setAn unordered data structure consisting of unique, immutable data values.
-
+
+ arraya data structure consisting of an ordered collection of data elements of identical type in which each element can be identified by an index.
+ wordunit of data used by a particular processor design.mutabilityable to be modified.immutableunable to be modified.
+ setAn unordered data structure consisting of unique, immutable data values.
+
Conditional statements in Python and C++ are very similar.
@@ -49,7 +50,7 @@ else {
simple example in both Python and C++.
-
+
# demonstrates if,elif, and else statements in python
def main():
grade = 85
@@ -66,12 +67,12 @@ def main():
print('A')
main()
-
+
In C++ we have a couple of ways to write this
-
+
// Shows how to use conditional statements
#include <iostream>
using namespace std;
@@ -104,16 +105,16 @@ main()
}
return 0;
}
-
+
-
We can get closer to the look of the elif statement in C++ by
+
We can get closer to the look of the elif elif statement in C++ by
taking advantage of the
C++ rule that a single statement does not need to be enclosed in curly
braces. Since the if is the only statement used in each else we can get
away with the following.
-
+
//Shows how to put conditional statements together,
//specfically putting "else if" after an "if" statement.
#include <iostream>
@@ -139,7 +140,7 @@ main()
return 0;
}
-
+
@@ -148,16 +149,16 @@ main()
switch
-
C++ also supports a switch statement that acts something like the
+
C++ also supports a switch switch statement that acts something like the
elif statement of Python under certain conditions because the statement
takes cases and checks the validity of the case against the code.
It uses cases instead of conditions and the case must be based on
- integers or a user-defined data type called an enumerated constant.
+ integers or a user-defined data type called an enumerated constant. enumerated constant
To write the grade
program using a switch statement we would use the following:
-
+
// Shows how to use a Switch statement.
#include <iostream>
@@ -189,20 +190,20 @@ main()
return 0;
}
-
+
Frankly, the switch statement is not used very often.
It is not as powerful as the else if model
because the switch variable can only be compared for equality with an
integer or something called an enumerated constant.
Second it is very easy to forget to put
- in the break statement. Note above how cases 10 and 9 are coded together.
+ in the break break statement. Note above how cases 10 and 9 are coded together.
If the break statement is left out then then
the next alternative will be automatically executed.
For example if the
grade was 95 and the break was omitted from the case 9:
alternative then the program would print out both (A and B.)
- So, you might want to just avoid it and use if…
+ So, you might want to just avoid it and use if…
Reading Questions
@@ -384,5 +385,4 @@ main()
-
-
+
\ No newline at end of file
diff --git a/pretext/Control_Structures/for_loop.ptx b/pretext/Control_Structures/for_loop.ptx
index 6a86e04..1c70c23 100644
--- a/pretext/Control_Structures/for_loop.ptx
+++ b/pretext/Control_Structures/for_loop.ptx
@@ -1,12 +1,13 @@
+
For Loops
Even though the while type of construct is very useful in a wide variety of
- situations, another iterative structure, the for statement, can be
+ situations, another iterative structure, the for for statement, can be
used to iterate across a range of values easily.
A for statement allows us to write a loop that is executed a specific number of times.
-
+
#include <iostream>
using namespace std;
@@ -15,14 +16,14 @@ int main() {
cout << i << "hello world" << endl;
}
}
-
+
In the example above, the hello world statement is executed 10 times.
A common use of the for construct is to implement certain repetition
over a range of values.
-
+
#include <iostream>
using namespace std;
@@ -35,7 +36,7 @@ using namespace std;
return 0;
}
-
+
The code will use cout five times. The value of the variable i will
start at 0 and go through the full sequence of values 0,1,2,3,4. This
@@ -112,5 +113,4 @@ int main() {
-
-
+
\ No newline at end of file
diff --git a/pretext/Control_Structures/summary.ptx b/pretext/Control_Structures/summary.ptx
index 58488d4..d093a1e 100644
--- a/pretext/Control_Structures/summary.ptx
+++ b/pretext/Control_Structures/summary.ptx
@@ -1,6 +1,6 @@
Summary & Reading Questions
-
+
Like Python C++ also supports the if-else conditional statements, and they behave the same way as they do in a Python program.
@@ -19,6 +19,6 @@
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
- breakTerminates the current block of code and resumes the program outside of it.caseCondition in a switch statement for a variable to be tested against.conditionalStatement that tests whether a condition is true or false .loopSeries of instructions repeated infinitely or until a condition is met.switchStatement that tests a variable against possible conditions for it.
+ breakTerminates the current block of code and resumes the program outside of it.caseCondition in a switch statement for a variable to be tested against.conditionalStatement that tests whether a condition is true or false .loopSeries of instructions repeated infinitely or until a condition is met.switchStatement that tests a variable against possible conditions for it.
diff --git a/pretext/Control_Structures/while_loop.ptx b/pretext/Control_Structures/while_loop.ptx
index 3c8dcd0..052fa46 100644
--- a/pretext/Control_Structures/while_loop.ptx
+++ b/pretext/Control_Structures/while_loop.ptx
@@ -5,7 +5,7 @@
Python in various forms. The programmer can choose the statement that is
most useful for the given circumstance.
For repeating a block of code, C++ provides a standard while and for constructs.
- The while construct repeats a body of code as long as a condition is true. For example,
+ The while while construct repeats a body of code as long as a condition is true. For example,
int counter = 1;
while (counter <= 5) { /*Use of an interactive method until the
the loop ends */
@@ -24,7 +24,7 @@ Hello, world
condition is true, the body of the statement will execute.
The while statement is a very general purpose iterative structure
that we will use in a number of different algorithms. In many cases, a
- compound condition will control the iteration. A fragment such as
+ compound condition compound condition will control the iteration. A fragment such as
while ((counter <= 10) && (!done)) {
...
would cause the body of the statement to be executed only in the case
diff --git a/pretext/Exception_Handling/ExceptionHandling.ptx b/pretext/Exception_Handling/ExceptionHandling.ptx
index b28daa9..aa9fedb 100644
--- a/pretext/Exception_Handling/ExceptionHandling.ptx
+++ b/pretext/Exception_Handling/ExceptionHandling.ptx
@@ -1,7 +1,7 @@
Exception Handling
There are two types of errors that typically occur when writing
- programs. The first, known as a syntax error, simply means that the
+ programs. The first, known as a syntax errorsyntax error, simply means that the
programmer has made a mistake in the structure of a statement or
expression. For example, it is incorrect to write a statement in one line and
forget the semicolon.
@@ -19,24 +19,25 @@
the processing of this instruction since it does not conform to the
rules of the language. Syntax errors are usually more frequent when you
are first learning a language.
-
The other type of error, known as a logic error, denotes a situation
+
The other type of error, known as a logic errorlogic error, denotes a situation
where the program executes but gives the wrong result. This can be due
to an error in the underlying algorithm or an error in your translation
of that algorithm. In some cases, logic errors lead to very bad
situations such as trying to divide by zero or trying to access an item
in a list where the index of the item is outside the bounds of the list.
- In this case, the logic error leads to a runtime error that causes the
+ In this case, the logic error leads to a runtime errorruntime error that causes the
program to terminate. These types of runtime errors are typically called
- exceptions.
+ exceptionsexception.
Most of the time, beginning programmers simply think of exceptions as
fatal runtime errors that cause the end of execution. However, most
- programming languages provide a way to deal with these errors that will
+ programming language provide a way to deal with these errors that will
allow the programmer to have some type of intervention if they so
choose. In addition, programmers can create their own exceptions if they
detect a situation in the program execution that warrants it.
-
When an exception occurs, we say that it has been thrown. You can
- catch the exception that has been raised by using a try
- statement. For example, consider the following session that asks the
+
When an exception occurs, we say that it has thrown an error.
+ throw an error You can
+ catchcatch the exception that has been raised by using a
+ try-catch statementtry-catch statement. For example, consider the following session that asks the
user for an integer and then uses the division operator.
If the user enters a second number that is not 0, then the print will show the result of division.
However, if the user enters 0, then C++ will throw an error and return a value other than 0.
@@ -54,7 +55,7 @@ exit status -1
-
+
// Shows exception handling using try,throw,
// and catch in order to output
// an error message to the console
@@ -88,17 +89,17 @@ int main() {
return 0;
}
-
+
This will catch the fact that an exception is raised by div and will
instead print the error back to the user.
This means that the program will not terminate but instead will continue
on to the next statements.
-
It is also possible for a programmer to use nested try and except statements,
+
It is also possible for a programmer to use nested try-catch statements,
along with different thrown errors to manage what happens in their code. The program
will continue running after the error is caught, but we can stop this by returning
- a value other than 0 in our main function. This is known as an error code.
+ a value other than 0 in our main function. This is known as an error codeerror code.
The code below should be run inside of a folder, and can be used to open files.
Ideally one of the files should be called file.txt. The program will prompt
the user for a filename and can catch if that file does not exist or the default
@@ -158,5 +159,4 @@ int main() {
There are many kinds of default exceptions that can be used in the C++ standard library.
See the C++ official documentation for a list
of all the available exception types and for how to create your own exception type.
-
-
+
\ No newline at end of file
diff --git a/pretext/Exception_Handling/Summary.ptx b/pretext/Exception_Handling/Summary.ptx
index e586b76..10c12c1 100644
--- a/pretext/Exception_Handling/Summary.ptx
+++ b/pretext/Exception_Handling/Summary.ptx
@@ -1,6 +1,6 @@
Summary & Reading Questions
-
+
There are two types of errors that occur while writing programs: syntax errors and logic errors
@@ -22,14 +22,14 @@
Click on the syntax error.
Remember, syntax errors occur more for people learning a new language.
-int age;:
-cout << "age:";:
-cin >> age;:
-if (age > 18) {:
+int age;
+cout << "age";
+cin >> age;
+if (age > 18) {
-cout << "You can vote in all countries with an 18 year old age for voting!";}:
-else {:
-cout << You cannot vote in all countries with an 18 year old age for voting.;:
+cout << "You can vote in all countries with an 18 year old age for voting!";}
+else {
+cout << You cannot vote in all countries with an 18 year old age for voting.;}
@@ -37,14 +37,14 @@
Click on the logic error.
If we want the code to say when we are old enough to vote, what cases should it say when can and cannot?
-int age;:
-cout << "age:";:
-cin >> age;:
-if (age > 18) {:
+int age;
+cout << "age";
+cin >> age;
+if (age < 18) {
-cout << "You can vote in all countries with an 18 year old age for voting!";}:
-else {:
-cout << You cannot vote in all countries with an 18 year old age for voting.;:
+cout << "You can vote in all countries with an 18 year old age for voting!";}
+else {
+cout << "You cannot vote in all countries with an 18 year old age for voting.";}
@@ -52,11 +52,11 @@
Match the words with their corresponding definition.
Feedback shows incorrect matches.
-
-exceptionResponse to an unusual circumstance while a program is running.
-logic error Error in which the program/code functions, but performs incorrectly.
-runtime errorError occurs when a program encounters an issue during its execution.
-syntax errorError in the structure of a statement or expression of code.
+
+exceptionResponse to an unusual circumstance while a program is running.
+logic error Error in which the program/code functions, but performs incorrectly.
+runtime errorError occurs when a program encounters an issue during its execution.
+syntax errorError in the structure of a statement or expression of code.
diff --git a/pretext/Figures/AtomicData/new_new_point12.png b/pretext/Figures/AtomicData/new_new_point12.png
index 36886e9..7bb3e92 100644
Binary files a/pretext/Figures/AtomicData/new_new_point12.png and b/pretext/Figures/AtomicData/new_new_point12.png differ
diff --git a/pretext/Figures/Input_and_Output/Write_Open.jpg b/pretext/Figures/Input_and_Output/Write_Open.jpg
index 9f38fa1..9232e5b 100644
Binary files a/pretext/Figures/Input_and_Output/Write_Open.jpg and b/pretext/Figures/Input_and_Output/Write_Open.jpg differ
diff --git a/pretext/Functions/ArraysAsParameter.ptx b/pretext/Functions/ArraysAsParameter.ptx
index ed40eb6..d50c76d 100644
--- a/pretext/Functions/ArraysAsParameter.ptx
+++ b/pretext/Functions/ArraysAsParameter.ptx
@@ -2,7 +2,7 @@
Arrays as Parameters in Functions
An array is a collection data type that is the ancestor of the Python list.
We will discuss arrays in more detail in the next chapter.
- Functions can be used with array parameters to maintain a structured design.
+ Functions can be used with array parametersarray parametersto maintain a structured design.
However, a formal parameter for an array is neither a call-by-value nor a call-by-reference,
but a new type of parameter pass called an array parameter.
In a function definition, an array parameter looks like a pass-by-value parameter
@@ -21,7 +21,7 @@
};
return (total / length);
}
-
Array parameters look like pass by value, but they are effectively similar to pass by reference parameters. When they execute, the functions with these parameters do not make private copies of the arrays. Instead, the reference is passed to reduce the impact on memory. Arrays can therefore always be permanently changed when passed as arguments to functions.
+
Array parameters look like pass by value, but they are effectively similar to pass by reference parameters. When they execute, the functions with these parameters do not make private copies of the arrays. Instead, the reference is passed to reduce the impact on memory. Arrays can therefore always be permanently changed when passed as arguments to functions.
After a call to the following function, each element in the third array argument is equal to the sum of the corresponding two elements in the first and second arguments:
void add_lists( int first[], int second[], int total[], int length ) {
//return type void which indicates that nothing is returned
@@ -29,7 +29,7 @@
for( count = 0; count < length; count++ ) {
total[count] = first[count] + second[count];
};}
-
Upon further examination, we can see that the first two arrays do not change values. To prevent ourselves from accidentally modifying any of these arrays, we can add the modifier const in the function head:
+
Upon further examination, we can see that the first two arrays do not change values. To prevent ourselves from accidentally modifying any of these arrays, we can add the modifier const const in the function head:
void add_lists( const int first[], const int second[], int total[], int length ) {
//return type void which indicates that nothing is returned
int count;
diff --git a/pretext/Functions/DefiningFunctions.ptx b/pretext/Functions/DefiningFunctions.ptx
index 55d66e0..d29a24f 100644
--- a/pretext/Functions/DefiningFunctions.ptx
+++ b/pretext/Functions/DefiningFunctions.ptx
@@ -9,7 +9,7 @@
-
+
#include <iostream>
using namespace std;
@@ -27,11 +27,11 @@ int main() {
return 0;
}
-
+
The syntax for this function definition includes the name, timesTwo,
- and a parenthesized list of formal parameters and their types. For this function an int named num
+ and a parenthesized list of formal parameters formal parameters and their types. For this function an int named num
is the only formal parameter, which suggests that timesTwo needs only
one piece of data to do its work. The details, hidden inside the box,
simply compute the result of num*2 and return it. We can invoke or
@@ -44,7 +44,7 @@ int main() {
-
+
#include <iostream>
using namespace std;
@@ -63,13 +63,13 @@ int main() {
return 0;
}
-
+
The timesTwoVoid function behaves very similarly to timesTwo. However, there is one key
difference between them. Instead of the int in timesTwo, timesTwoVoid has a
- void in front of its function definition. Unlike timesTwo, timesTwoVoid is a non-fruitful
- function meaning it does not return a value even though it can still print something out.
+ void void in front of its function definition. Unlike timesTwo, timesTwoVoid is a non-fruitful
+ function non-fruitful function meaning it does not return a value even though it can still print something out.
We could go a step further and implement our own square root function by using a well-known
technique called Newton's Method. Newton's Method for approximating
square roots performs an iterative computation that converges on the
@@ -78,18 +78,17 @@ int main() {
takes a value n and repeatedly guesses the square root by
making each newguess the oldguess in the subsequent
iteration. The initial guess used here is \frac {n}{2}.
- Listing 1 shows a function definition that accepts a value
+ shows a function definition that accepts a value
n and returns the square root of n after making 20
guesses. Again, the details of Newton's Method are hidden inside the
function definition and the user does not have to know anything about
the implementation to use the function for its intended purpose.
- Listing 1 also shows the use of the // characters as a comment
+ also shows the use of the // characters as a comment
marker. Any characters that follow the // on a line are ignored.
-
-
Listing 1
-
+
+
-
+
// returns the square root of a number as a double
#include <iostream>
using namespace std;
@@ -111,13 +110,13 @@ int main() {
return 0;
}
-
+
-
+
-
-// function that retuns outputs number of steps wallked
+
+// function that returns the output number of steps walked
#include <iostream>
using namespace std;
@@ -132,7 +131,7 @@ int main() {
return 0;
}
-
+
diff --git a/pretext/Functions/FunctionOverloading.ptx b/pretext/Functions/FunctionOverloading.ptx
index 4d4d835..a94f135 100644
--- a/pretext/Functions/FunctionOverloading.ptx
+++ b/pretext/Functions/FunctionOverloading.ptx
@@ -1,6 +1,6 @@
Function Overloading
-
Function overloading is the ability to create multiple functions with identical names but different implementations.
+
Function overloadingfunction overloading is the ability to create multiple functions with identical names but different implementations.
Not all languages support function overloading. Python does not, for example.
In C++ programming, two or more functions can have same
name when they can be distinguished by the parameters.
@@ -14,7 +14,7 @@
-
+
// demonstrates how function overloading works
// by changing the parameters on the inputs.
#include <iostream>
@@ -37,12 +37,12 @@ int main() {
return 0;
}
-
+
-
+
"""Demonstrates the use of multiple parameters using a single function"""
def myfunct(n, m=None):
if m is None:
@@ -57,7 +57,7 @@ def main():
myfunct(100);
main()
-
+
@@ -74,7 +74,7 @@ main()
-
Helps keep consintency in the way your functions are named across your program.
+
Helps keep consistency in the way your functions are named across your program.
Take a look at the other answers as well...
@@ -139,7 +139,7 @@ main()
Self Check Challenge
See if you can improve upon the program in the self check by keeping letters
that are correct and only modifying one character in the best string so far.
- This is a type of algorithm in the class of ‘hill climbing' algorithms, that
+ This is a type of algorithm in the class of ‘hill climbing' algorithms, that
is we only keep the result if it is better than the previous one.
diff --git a/pretext/Functions/ParameterPassingByValue.ptx b/pretext/Functions/ParameterPassingByValue.ptx
index ef24c7e..d3c619a 100644
--- a/pretext/Functions/ParameterPassingByValue.ptx
+++ b/pretext/Functions/ParameterPassingByValue.ptx
@@ -1,7 +1,7 @@
Parameter Passing: by Value versus by Reference
In all of the functions we have written thus far, we have used a function calling
- mechanism called pass by value.
+ mechanism called pass by valuepass by value.
Calling a function by value involves copying the contents of the arguments
into the memory locations of the corresponding formal parameters.
If the function changes
@@ -30,7 +30,7 @@ void callingFunction() { /*return type void which indicates
so the cout statement within this function produces the output:
nextVar = 20 inputVar = 4
Notice what happens when functionExample(...) ends and execution returns to callingFunction().
- The contents of myVar is still the same, as the location for myVar differs from where inputVar
+ The contents of myVar is still the same, as the location for myVar differs from where inputVar
is stored. Thus, myVar still has the value 10, and the cout statement after the function call will
produce the output:
myVar = 10
@@ -39,7 +39,7 @@ void callingFunction() { /*return type void which indicates
However, there is a problem.
We have seen examples of C++ functions that return no value or a single value.
How about when we want the function to return more than one value?
- We need another function calling mechanism called pass by reference.
+ We need another function calling mechanism called pass by referencepass by reference.
When using this mechanism, the actual location in memory referenced by the arguments are
sent rather than the values in that location.
To let the compiler know that you intend to use pass by reference,
@@ -54,7 +54,7 @@ void callingFunction() { /*return type void which indicates
-
+
#include <iostream>
using namespace std;
@@ -81,14 +81,14 @@ int main( ) {
return 0;
}
-
+
-
For this program Swap Inputs to reverse the order of the integers the users types in, the function swap_values(...) must be able to change the values of the arguments. Try removing one or both of the & ‘s in this code to see what happens.
+
For this program Swap Inputs to reverse the order of the integers the users types in, the function swap_values(...) must be able to change the values of the arguments. Try removing one or both of the & ‘s in this code to see what happens.
Analyze the program and answer the question that involves parameter passing below:
-
+
// demonstrates the difference between pass-by-value
// and pass-by-reference functions.
#include <iostream>
@@ -121,7 +121,7 @@ int main(){
return 0;
}
-
+
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
- argumentData passed to parameter.function Section of code that performs a procedure and usually is named meaningfully.overloadingSpecifying more than one definition for the same function name.
+ argumentData passed to parameter.function Section of code that performs a procedure and usually is named meaningfully.overloadingSpecifying more than one definition for the same function name.
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
-
- parameterVariable in a function or method definition that accepts data passed from an argument.referenceValue that indicates an address in a computer's memory.voidindicates a function has no return value.
- constindicates a variable or value is unchanging.
+
+ parameterVariable in a function or method definition that accepts data passed from an argument.referenceValue that indicates an address in a computer's memory.voidindicates a function has no return value.
+ constindicates a variable or value is unchanging.
-
+
-
-
+
\ No newline at end of file
diff --git a/pretext/Input_and_Output/DealingWithIOFailures.ptx b/pretext/Input_and_Output/DealingWithIOFailures.ptx
index 028147e..b9aa85e 100644
--- a/pretext/Input_and_Output/DealingWithIOFailures.ptx
+++ b/pretext/Input_and_Output/DealingWithIOFailures.ptx
@@ -8,17 +8,37 @@
the system call to open a file returns a value after the function is called.
A negative number means the operation failed for some reason, which the program can
check to see if reading from a file is alright. In C++, a simple error checking mechanism
- is provided by the member function fail():
+ is provided by the member function fail(): fail()
in_stream.fail();
This function returns true only if the previous stream operation for in_stream
was not successful, such as if we tried to open a non-existent file. If a failure has
occured, in_stream may be in a corrupted state and it is best not to attempt any more
operations with it.
The following example code fragment safely quits the program entirely in case an I/O operation fails:
After opening the myFile.txt file, the if conditional checks to see if there was an error. If so, the program will output the apologetic error message and then exit. The exit(1) function from the library cstdlib enables the program to terminate at that point and have it return a 1 versus a 0, indicating an Error has occurred.
+
+
+
+ #include <cstdlib< // for the fail member function
+ #include <fstream< // for file I/O definitions
+ #include <iostream< // for cout definition
+ using namespace std;
+
+ int main() {
+ ifstream in_stream;
+ // Try changing this to realFile.txt
+ in_stream.open("realFile.txt");
+ if (in_stream.fail()) {
+ cout << "Sorry, the file couldn't be opened!\n";
+ exit(1); // This exit value indicates an error happened (usual exit
+ // value is 0)
+ }
+
+ return 0;
+ }
+
+
+
+
After opening the myFile.txt file, the if conditional checks to see if there was an error. If so, the program will output the apologetic error message and then exit. The exit(1) exit() function from the library cstdlib enables the program to terminate at that point and have it return a 1 versus a 0, indicating an Error has occurred.
For more on Error Handling, see section 1.11.
diff --git a/pretext/Input_and_Output/FileNameAndCString.ptx b/pretext/Input_and_Output/FileNameAndCString.ptx
index 1ef9e3c..f1ac735 100644
--- a/pretext/Input_and_Output/FileNameAndCString.ptx
+++ b/pretext/Input_and_Output/FileNameAndCString.ptx
@@ -8,7 +8,7 @@
filenames that the program will use instead of the same names.
We have previously talked about the char data type that allows users to store
and manipulate a single character at a time. A sequence of characters such as myFileName.dat
- can be stored in an array of chars called a c-string, which can be declared as follows:
+ can be stored in an array of chars called a c-string c-string , which can be declared as follows:
Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function open(filename). For example, the following statement will allow the C++ program to open the file called myFile.txt, assuming a file named that exists in the current directory, and connect in_stream to the beginning of the file:
+
Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function open(Filename) open(filename) . For example, the following statement will allow the C++ program to open the file called myFile.txt, assuming a file named that exists in the current directory, and connect in_stream in_stream to the beginning of the file:
in_stream.open("myFile.txt");
Once connected, the program can read from that file. Pictorially, this is what happens:
-
the <ofstream> class also has an open(filename) member function, but it is defined differently. Consider the following statement:
+
the <ofstream> ofstream class also has an open(filename) member function, but it is defined differently. Consider the following statement:
out_stream.open("anotherFile.txt");
Pictorally, we get a stream of data flowing out of the program:
Because out_stream is an object of type <ofstream>, connecting it to the file named anotherFile.txt will create that file if it does not exist. If the file anotherFile.txt already exists, it will be wiped and replaced with whatever is fed into the output stream.
-
To disconnect the ifstream in_stream from whatever file it opened, we use its close() member function:
+
To disconnect the ifstream ifstream in_stream from whatever file it opened, we use its close() member function:
close()
in_stream.close();
To close the file for out_stream, we use its close() function, which also adds an end-of-file marker to indicate where the end of the file is:
out_stream.close();
-
Answer the question below concerning the use of the fstream library:
+
Answer the question below concerning the use of the fstream library:
fstream Reading Question
diff --git a/pretext/Input_and_Output/MemberFunctionAndPrecision.ptx b/pretext/Input_and_Output/MemberFunctionAndPrecision.ptx
index eb96cee..954f0a5 100644
--- a/pretext/Input_and_Output/MemberFunctionAndPrecision.ptx
+++ b/pretext/Input_and_Output/MemberFunctionAndPrecision.ptx
@@ -1,6 +1,6 @@
Member Functions and Precision
-
A function that is associated with a certain type of object is called a member function of that object. You have already used member functions setf(...) and precision(...) for formatting our output streams using cout. These functions are included briefly below:
+
A function that is associated with a certain type of object is called a member functionmember function of that object. You have already used member functions setf(...) and precision(...) for formatting our output streams using cout. These functions are included briefly below:
// Use cout's member function "set flags", called setf
// The argument here means to use a fixed point rather than scientific notation
cout.setf(ios::fixed);
diff --git a/pretext/Input_and_Output/PuttingItAllTogether.ptx b/pretext/Input_and_Output/PuttingItAllTogether.ptx
index ff68f0d..16bbc7f 100644
--- a/pretext/Input_and_Output/PuttingItAllTogether.ptx
+++ b/pretext/Input_and_Output/PuttingItAllTogether.ptx
@@ -1,64 +1,66 @@
Putting it all Together
The following program combines all of the elements above and asks the user for the input and output filenames. After testing for open failures, it will read three numbers from the input file and write the sum into the output file.
-
#include <cstdlib> // for the exit function
-#include <fstream> // for I/O member functions
-#include <iostream> // for cout
-using namespace std; // To avoid writing std:: before standard library components
+
+
+
+ #include <cstdlib> // for the exit function
+ #include <fstream> // for I/O member functions
+ #include <iostream> // for cout
+ using namespace std; // To avoid writing std:: before standard library components
-int main() {
- // Declare variables for file names and file streams
- char in_file_name[16], // Arrays to store filenames (max 15 chars + null terminator)
- out_file_name[16];
- ifstream in_stream; // Input file stream object
- ofstream out_stream;// Output file stream object
+ int main() {
+ // Declare variables for file names and file streams
+ char in_file_name[16], // Arrays to store filenames (max 15 chars + null terminator)
+ out_file_name[16];
+ ifstream in_stream; // Input file stream object
+ ofstream out_stream;// Output file stream object
- // Prompt the user for input and output file names
- cout << "This program will sum three numbers taken from an input\n"
- << "file and write the sum to an output file." << endl;
- cout << "Enter the input file name (maximum of 15 characters):\n";
- cin >> in_file_name;
- cout << "\nEnter the output file name (maximum of 15 characters):\n";
- cin >> out_file_name;
- cout << endl;
+ // Prompt the user for input and output file names
+ cout << "This program will sum three numbers taken from an input\n"
+ << "file and write the sum to an output file." << endl;
+ cout << "Enter the input file name (maximum of 15 characters):\n";
+ cin >> in_file_name;
+ cout << "\nEnter the output file name (maximum of 15 characters):\n";
+ cin >> out_file_name;
+ cout << endl;
- // Condensed input and output file opening and checking.
- in_stream.open(in_file_name);
- out_stream.open(out_file_name);
+ // Condensed input and output file opening and checking.
+ in_stream.open(in_file_name);
+ out_stream.open(out_file_name);
- if (in_stream.fail() || out_stream.fail()) {
- cout << "Input or output file opening failed.\n";
- exit(1); // Terminate the program with an error code
- }
+ if (in_stream.fail() || out_stream.fail()) {
+ cout << "Input or output file opening failed.\n";
+ exit(1); // Terminate the program with an error code
+ }
- // Declare variables to store numbers and their sum
- double firstn, secondn, thirdn, sum = 0.0;
+ // Declare variables to store numbers and their sum
+ double firstn, secondn, thirdn, sum = 0.0;
- // Read the first three numbers from the input file
- cout << "Reading numbers from the file " << in_file_name << endl;
- in_stream >> firstn >> secondn >> thirdn;
- sum = firstn + secondn + thirdn;
+ // Read the first three numbers from the input file
+ cout << "Reading numbers from the file " << in_file_name << endl;
+ in_stream >> firstn >> secondn >> thirdn;
+ sum = firstn + secondn + thirdn;
- // The following set of lines will write to the screen
- cout << "The sum of the first 3 numbers from " << in_file_name << " is "
- << sum << endl;
+ // The following set of lines will write to the screen
+ cout << "The sum of the first 3 numbers from " << in_file_name << " is "
+ << sum << endl;
- cout << "Placing the sum into the file " << out_file_name << endl;
+ cout << "Placing the sum into the file " << out_file_name << endl;
- // The following set of lines will write to the output file
- out_stream << "The sum of the first 3 numbers from " << in_file_name
- << " is " << sum << endl;
+ // The following set of lines will write to the output file
+ out_stream << "The sum of the first 3 numbers from " << in_file_name
+ << " is " << sum << endl;
- // Close the file streams
- in_stream.close();
- out_stream.close();
+ // Close the file streams
+ in_stream.close();
+ out_stream.close();
- cout << "End of Program." << endl;
+ cout << "End of Program." << endl;
- return 0;
-}
File handling in C++ uses stream similar to cout and cin in <iosteam> library but is <fstream> for file stream.
@@ -68,7 +68,7 @@
Drag the corresponding library to what you would use it for.
Which library is used for which task?
-fstreamI want to write to a fileiostreamI want to write to the console
+fstreamI want to write to a fileiostreamI want to write to the console
@@ -110,11 +110,10 @@
Match the words to thier corresponding definition.
Feedback shows incorrect matches.
-
- streamAn abstraction that allows you to send or receive an unknown number of bytes in input or output.
- member functionA function that's associated with a certain type of object.c-stringAn array of characters that ends with a terminating null character.End-Of-FileA flag that lets programs know when to stop.
-
+
+ streamAn abstraction that allows you to send or receive an unknown number of bytes in input or output.
+ member functionA function that's associated with a certain type of object.c-stringAn array of characters that ends with a terminating null character.End-Of-FileA flag that lets programs know when to stop.
+
-
-
+
\ No newline at end of file
diff --git a/pretext/Input_and_Output/TheEOF.ptx b/pretext/Input_and_Output/TheEOF.ptx
index 0b89c5d..8f1a640 100644
--- a/pretext/Input_and_Output/TheEOF.ptx
+++ b/pretext/Input_and_Output/TheEOF.ptx
@@ -7,7 +7,7 @@
Otherwise, they could read data from a different file that happened to be
right after it in the hard drive, which can be disastrous.
Many development environments have I/O libraries that define how the member
- function eof() works for ifstream variables to test if this flag is set to true or false. Typically, one would like to know when the EOF has not been reached, so a common way is a negative boolean value. An alternative implementation is to keep reading using the >> operator; if that operation was successful (i.e. there was something in the file that was read), this success is interpreted as a 1 (true).
+ function eof() eof() works for ifstream variables to test if this flag is set to true or false. Typically, one would like to know when the EOF has not been reached, so a common way is a negative boolean value. An alternative implementation is to keep reading using the >> operator; if that operation was successful (i.e. there was something in the file that was read), this success is interpreted as a 1 (true).
Incidentally, that is why if you forget the second equals sign in a comparison
between a variable and a value, you are assigning the value to the variable,
which is a successful operation, which means the condition ends up evaluating to true.
@@ -26,67 +26,72 @@
Here is an example of a program that essentially uses the second technique
mentioned above to read all the numbers in a file and output them in a neater format.
The while loop to scan through a file is located in the make_neat(...) function.
-
// Illustrates output formatting instructions.
-// Read all the numbers in the file rawdata.dat and write the numbers
-// to the screen and to the file neat.dat in a neatly formatted way.
+
+
+
+ // Illustrates output formatting instructions.
+ // Read all the numbers in the file rawdata.dat and write the numbers
+ // to the screen and to the file neat.dat in a neatly formatted way.
-#include <cstdlib> // for the exit function
-#include <fstream> // for I/O member functions
-#include <iomanip> // for the setw function
-#include <iostream> // for cout
-using namespace std;
-void make_neat(
- ifstream &messy_file,
- ofstream &neat_file,
- int number_after_decimalpoint,
- int field_width);
+ #include <cstdlib> // for the exit function
+ #include <fstream> // for I/O member functions
+ #include <iomanip> // for the setw function
+ #include <iostream> // for cout
+ using namespace std;
+ void make_neat(
+ ifstream &messy_file,
+ ofstream &neat_file,
+ int number_after_decimalpoint,
+ int field_width);
-int main() {
- ifstream fin;
- ofstream fout;
+ int main() {
+ ifstream fin;
+ ofstream fout;
- fin.open("rawdata.txt");
- if (fin.fail()) { // oops the file did not exist for reading?
- cout << "Input file opening failed." << endl;
- exit(1);
- }
+ fin.open("rawdata.txt");
+ if (fin.fail()) { // oops the file did not exist for reading?
+ cout << "Input file opening failed." << endl;
+ exit(1);
+ }
- fout.open("neat.txt");
- if (fout.fail()) { // oops the output file open failed!
- cout << "Output file opening failed.\n";
- exit(1);
- }
- make_neat(fin, fout, 5, 12);
+ fout.open("neat.txt");
+ if (fout.fail()) { // oops the output file open failed!
+ cout << "Output file opening failed.\n";
+ exit(1);
+ }
+ make_neat(fin, fout, 5, 12);
- fin.close();
- fout.close();
- cout << "End of program." << endl;
- return 0;
-}
-// Uses iostreams, streams to the screen, and iomanip:
-void make_neat(
- ifstream &messy_file,
- ofstream &neat_file,
- int number_after_decimalpoint,
- int field_width) {
- // set the format for the neater output file.
- neat_file.setf(ios::fixed);
- neat_file.setf(ios::showpoint);
- neat_file.setf(ios::showpos);
- neat_file.precision(number_after_decimalpoint);
- // set the format for the output to the screen too.
- cout.setf(ios::fixed);
- cout.setf(ios::showpoint);
- cout.setf(ios::showpos);
- cout.precision(number_after_decimalpoint);
- double next;
- while (messy_file >> next) { // while there is still stuff to read
- cout << setw(field_width) << next << endl;
- neat_file << setw(field_width) << next << endl;
- }
-}
-
-// Code by Jan Pearce
+ fin.close();
+ fout.close();
+ cout << "End of program." << endl;
+ return 0;
+ }
+ // Uses iostreams, streams to the screen, and iomanip:
+ void make_neat(
+ ifstream &messy_file,
+ ofstream &neat_file,
+ int number_after_decimalpoint,
+ int field_width) {
+ // set the format for the neater output file.
+ neat_file.setf(ios::fixed);
+ neat_file.setf(ios::showpoint);
+ neat_file.setf(ios::showpos);
+ neat_file.precision(number_after_decimalpoint);
+ // set the format for the output to the screen too.
+ cout.setf(ios::fixed);
+ cout.setf(ios::showpoint);
+ cout.setf(ios::showpos);
+ cout.precision(number_after_decimalpoint);
+ double next;
+ while (messy_file >> next) { // while there is still stuff to read
+ cout << setw(field_width) << next << endl;
+ neat_file << setw(field_width) << next << endl;
+ }
+ }
+ // Code by Jan Pearce
+
+
+
This is the rawdata.txt inputed into the make_neat(...).
The input file rawdata.txt must be in the same directory (folder) as the program in order for it to open successfully. The program will create a file called neat.dat to output the results.
What we see is that at the core there are a few similarities with the
complicated Python version, such as the main function and the
@@ -62,7 +62,7 @@ int main(){
A question you may have about this little program is How would I run it on
my own machine? Running a C++ program is not as simple as running a
Python program. The first big difference between C++ and Python is that
- Python is an interpreted language while C++ is a compiled language.
+ Python is an interpreted languageinterpreted language while C++ is a compiled languagecompiled language .
We could run our Python programs in
the Python interpreter, and we were often quite happy to do that.
In C++, running programs is a two step process.
@@ -83,7 +83,7 @@ int main(){
The job of the compiler is to turn your C++ code into language that your
machine can understand. We call the code that the computer
- understands machine code. The computer interprets the machine code
+ understands machine codemachine code . The computer interprets the machine code
much like the Python interpreter interprets your Python.
However, since machine code is much closer to the native language of the
computer, it can run faster.
@@ -97,13 +97,15 @@ int main(){
Using headers and libraries
-
Preprocessor directives in C++ appear as statements preceded by the hash sign #.
+
+ Preprocessor directivespreprocessor directives
+ in C++ appear as statements preceded by the hash sign # # .
These tell the preprocessor which file, header, or library to make available to
- the compiler. For example, #include <iostream> will make sure that
+ the compiler. For example, #include <iostream> iostream will make sure that
the iostream library is available at compile time.
- Here, the term header is used for a type of C++ file that contains definitions
+ Here, the term headerheaderis used for a type of C++ file that contains definitions
of functions and variables, but not the function implementations.
-
You can think of the #include ... statement in C++ as working a bit like
+
You can think of the #include ... #include statement in C++ as working a bit like
the import ... statement in Python.
Python's import statement directly accesses the code written in another file
while the #include statement in C++ copies classes and functions from
@@ -113,37 +115,37 @@ int main(){
There are two ways to use #include in C++:
#include <libraryname>
#include "filename"
-
Here the angle-brackets <> are used to include libraries or headers provided by
+
Here the angle-brackets <> <> are used to include libraries or headers provided by
the implementation, such as the
headers in the standard library (iostream, string, etc.). The double
- quotes " are used for headers and files not provided by the implementation.
+ quotes " "" are used for headers and files not provided by the implementation.
The main function
Unlike Python, every C++ program must have a main function which begins
- with int main(). This main function is called implicitly instead of
+ with int main(). This main main function is called implicitly instead of
explicitly like we must do in Python when we have a main function. This is
why you do not see an explicit function call invoking main.
-
The int in int main() indicates that the return type of the main function will be
- an integer. The final line of the main C++ function is typically return 0,
+
The int in int main() indicates that the return type of the main function will be
+ an integer. The final line of the main C++ function is typically return 0 return 0 ,
so you can see that the program does actually return the integer 0.
Here zero is returned to indicate successful completion of the main
function. In case you are wondering why an integer is returned, if you do error
handling in C++, instead of 0, you can alternatively return an integer error code representing
a specific error when and where it occurs.
-
C++ functions and other C++ code blocks are grouped together using the curly {}
- brackets. These curly brackets are used much like tabbing is used in Python.
+
C++ functions and other C++ code blocks are grouped together using the curly {} {}
+ brackets. These curly brackets curly brackets are used much like tabbing is used in Python.
Many people also use tabbing in C++ to indicate blocks, but tabs and other
whitespace (mostly) have no inherent meaning in C++.
- Instead, the semi-colon (;) must be used to conclude most statements in C++.
+ Instead, the semi-colon semi-colon (;) ; must be used to conclude most statements in C++.
In fact, the following program will run perfectly
even though the lack of meaningful spacing is more difficult for humans to read.
-
+
#include <iostream>
using namespace std; int main(){cout << "Hello World!\n"; return 0;}
-
+
As you program in C++, we strongly recommend you continue to use
the kind of human-readable formatting you have become used to in Python.
@@ -154,12 +156,13 @@ using namespace std; int main(){cout << "Hello World!\n"; return 0;}
Comments in C++
Python and C++ both support comments that are not processed by the interpreter or compiler.
Python's single line comment begins with a hash (#).
- In C++, the equivalent is two forward slashes (//)
+ In C++, the equivalent is two forward slashes (//) //
In each case the rest of the line is treated as a comment and ignored by the
interpreter or compiler.
Python supports comments using triple quotes.
Like Python, C++ also supports multi-line comments
beginning with
+ /* */ /*
and ending with
*/.
@@ -167,6 +170,7 @@ using namespace std; int main(){cout << "Hello World!\n"; return 0;}
processing documentation.
There is no equivalent in the C++ standard to the triple-quoted docstring in Python.
However, the symbol groups
+ /** */ /**
and
*/
@@ -188,18 +192,18 @@ span many lines, beginning and ending with the given symbols */
from the standard input as well as to output information to the standard output. This input and output is handled by what
is known as a stream.
A stream is essentially a channel in which data flows from the source to a destination (often called the sink.)
- Output streams send data out, and the standard output stream cout sends character data to the screen.
+ Output streams send data out, and the standard output stream cout cout sends character data to the screen.
So, cout stands for character output.
Much like the Python print statement, cout is used to
print to the standard output device, which is typically your screen.
- When cout is used, you will also see << used.
- When this odd set of symbols are used together, they are called the output operator.
+ When cout is used, you will also see << << used.
+ When this odd set of symbols are used together, they are called the output operatoroutput operator<<.
The output operator is used to direct output to the designated output device or file.
The output operator can also be used to concatenate output, much like the +
can be used to concatenate in Python.
In addition to being able to output to the standard output, we want to be able to take input from the user.
The command cin is somewhat similar to cout except, of course, it is used for getting character input.
Input streams direct data from a source, such as the keyboard or a file.
- As you might have guessed, cin stands for character input and it makes getting input from the standard input device (usually the keyboard) relatively easy.
- The input operator in C++ is >>.
+ As you might have guessed, cin cin stands for character input and it makes getting input from the standard input device (usually the keyboard) relatively easy.
+ The input operator input operator>> in C++ is >> >> .
Here is an example that uses cin:
@@ -230,7 +234,7 @@ int main(){
-
+
#include <iostream>
using namespace std;
@@ -250,14 +254,14 @@ int main() {
return 0;
}
-
+ Type Declarations
In this example, you may note the line float num which declares a new variable called num of type float.
Just like functions, all variables in C++ must be declared before use, and
- they cannot change type. This is known as static typing.
+ they cannot change type. This is known as static typing static typing .
The line float num essentially tells the compiler to set aside sufficient space for a floating point number,
and to name this memory location num.
Then whatever the user types in will be stored in the num variable.
@@ -271,9 +275,18 @@ int main() {
Reading Questions
Match Compiler and Interpreter to the correct definition.
-
This is feedback.
- Compilergenerally transforms code written in a high-level language into a low-level language in order to create an executable programInterpreterdirectly executes statements in a scripting language without requiring them to have been assembled into machine language
+
+
+ Compiler
+ generally transforms code written in a high-level language into a low-level language in order to create an executable program
+
+
+ Interpreter
+ directly executes statements in a scripting language without requiring them to have been assembled into machine language
+
+
+
Correctly rearrange the code below to implement hello world in C++:
Once we have the basics of C++ behind us we will move on to look at the
- additonal useful features of C++ including:
+ additional useful features of C++ including:
diff --git a/pretext/IntroCpp/summary.ptx b/pretext/IntroCpp/summary.ptx
index aded5d1..fc58033 100644
--- a/pretext/IntroCpp/summary.ptx
+++ b/pretext/IntroCpp/summary.ptx
@@ -4,7 +4,7 @@
Now that we have run our “hello world” program, lets go back and look at it carefully to see what we can learn about the C++ language.
-
+
/* This hello world program demonstrates the C++ concepts
of commenting, using libraries, and using output.
*/
@@ -15,12 +15,12 @@ int main(){ // main() must exist & return an int
cout << "Hello World!\n";
return 0; // 0 indicates program ended correctly.
}
-
+
This simple example illustrates a few very important rules:
-
+
Everything in C++ must be declared as a specific type of object or variable, including declaring the return type for each function.
@@ -62,7 +62,7 @@ int main(){ // main() must exist & return an int
-
+
//
@@ -71,7 +71,7 @@ int main(){ // main() must exist & return an int
-
+
@
@@ -80,7 +80,7 @@ int main(){ // main() must exist & return an int
-
+
none of the above
@@ -107,7 +107,7 @@ int main(){ // main() must exist & return an int
-
+
False
@@ -153,7 +153,7 @@ int main(){ // main() must exist & return an int
-
+
none of the above
@@ -165,7 +165,7 @@ int main(){ // main() must exist & return an int
-
+
What keyword from the Standard Library (std) is used in conjunction with the extraction operator to accept C++ input from the keyboard as the standard input?
Right! It stands for character input.
@@ -177,34 +177,64 @@ int main(){ // main() must exist & return an int
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
-
- dynamically typedPrograming language, in which variables need not necessarily be defined before they are used, and can change during execution.
- statically typedProgramming language, in which variables must be defined before they are used and cannot change during execution.commenta readable explanation in the source code of a computer program.
-
+
+ dynamically typedPrograming language, in which variables need not necessarily be defined before they are used, and can change during execution.
+ statically typedProgramming language, in which variables must be defined before they are used and cannot change during execution.commenta readable explanation in the source code of a computer program.
+
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
-
-
- #includeTells the preprocessor to treat the contents of a specified file as if they appear in the source program at the point where the directive appears.
- headerlibrary files that contain a variety of useful definitions. They are imported into any C++ program by using the #include statement.
- cinStandard input statement in C++.
- coutStandard output statement in C++.
-
-
+
+
+
+ #include
+ Tells the preprocessor to treat the contents of a specified file as if they appear in the source program at the point where the directive appears.
+
+
+
+ header
+ Library files that contain a variety of useful definitions. They are imported into any C++ program by using the #include statement.
+
+
+
+ cin
+ Standard input statement in C++.
+
+
+
+ cout
+ Standard output statement in C++.
+
+
+
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
-
+
+
+ #include
+ Tells the preprocessor to treat the contents of a specified file as if they appear in the source program at the point where the directive appears.
+
+
+
+ header
+ Library files that contain a variety of useful definitions. They are imported into any C++ program by using the #include statement.
+
+
+
+ cin
+ Standard input statement in C++.
+
- compilerCreates an executeable program by transforming code written in a high-level programming language into a low-level programming language.
- interpreterdirectly executes statements in a scripting language without requiring them to have been compiled into machine languagemachine code a computer program written in instructions that can be directly executed by a computer's CPU.
-
-
+
+ cout
+ Standard output statement in C++.
+
+
diff --git a/pretext/Turtles/advanced_features.ptx b/pretext/Turtles/advanced_features.ptx
index 90bc5e1..ec6226f 100644
--- a/pretext/Turtles/advanced_features.ptx
+++ b/pretext/Turtles/advanced_features.ptx
@@ -53,39 +53,39 @@
Regarding angles, Turtles can use both degrees and radians for their rotations. You can choose between the two using the
radians and degrees methods for the Turtle object. By default, all angles are measured in degrees. This option
only effects methods regarding rotation, such as left and right.
-
+
turtle.degrees();
turtle.right(90);//90-degree turn to the right
turtle.radians();
turtle.left(1.5708f);//Equivalent rotation in radians to the left.
-
+
The tracer(N) method is used to control how many times the Turtle is actually
drawn on the screen. This method belongs to the TurtleScreen object, and effects
all turtles that are on the screen. The N in the method represents the input,
only allowing the TurtleScreen to display one frame out every N.
-
+
screen.tracer(12);
//Show one out of every 12 frames of animation.
-
+
This can be combined with the speed method available to turtles to achieve very quickly
drawn images. The maximum speed a Turtle can have, TS_FASTEST, completely disables animation
for Turtles between movements and rotations. This allows the tracer setting to directly relate
to the total number of actions the turtle makes. The actions the turtle takes happen regardless
of whether or not they are actually shown on the screen.
-
+
screen.tracer(3); //Show one out of every 3 frames of animation.
turtle.speed(ct::TS_FASTEST); //Disables Turtle animation
turtle.forward(50);//This is not shown on-screen...
turtle.right(90);//Neither is this...
turtle.forward(50);//But this action is, because it is third out of three.
-
+
A frame of animation is added for almost every action a turtle takes, regardless of whether or not
the turtle is moving or adding something to the screen. This includes methods like
begin_fill and end_fill, which don't do anything visually but do
tell the turtle to start or stop tracking its own movements.
Consider the following example and related questions.
Similarly to tracer settings, every action a turtle takes is also added to the undo queue. This allows it to keep track
diff --git a/pretext/Turtles/differences.ptx b/pretext/Turtles/differences.ptx
index c7e9840..4d06dad 100644
--- a/pretext/Turtles/differences.ptx
+++ b/pretext/Turtles/differences.ptx
@@ -2,9 +2,9 @@
Python's turtle vs C-Turtle
C-Turtle varies from the Python turtle library primarily in syntax. Most of the methods
are exactly the same between implementations, however there are a few notable differences between the two.
- Colors, for example, must be surrounded by curly brackets (e.g, ‘{' and ‘}') when referring to them by a
+ Colors, for example, must be surrounded by curly brackets (e.g, ‘{' and ‘}') when referring to them by a
name such as red, green, or blue. You can also ask for a random color by using the string random.
-
+
ct::Color red = {"red"};
ct::Color green = {"green"};
ct::Color blue = {"blue"};
@@ -16,7 +16,7 @@ turtle.pencolor(red);
//And so do these.
turtle.pencolor({"green"});
turtle.pencolor({"random"});
-
+
Unlike in Python, the write method does not allow you to specify a font nor size. In contrast to Python, C++ finds it much more challenging to handle fonts because operating systems deal with them in a complex way.
Furthermore, there is no world screen mode like
there is in Python. Normally, this would allow you to specify the bounds of your canvas (e.g, specify minimum
@@ -28,17 +28,17 @@ turtle.pencolor({"random"});
The former of the two, shift, simply adds to the X and Y coordinate position of the turtle. If your turtle is at coordinate
600x, 400y and shift is called with coordinate 50x and -50y, the turtle's final position would be 650x, 350y. The latter
of the two, middle, returns the point exactly between two other points. See the examples below.
-
+
turtle.goTo(600, 400);
turtle.shift(50, -50);
//Turtle position is now 650x, 350y.
-
-
+
+
ct::Point a = {400, 300};
ct::Point b = {450, 300};
//Should equal the point 425x, 300y.
ct::Point middle = ct::middle(a, b);
-
+
diff --git a/pretext/Turtles/geometry_shapes_stamps.ptx b/pretext/Turtles/geometry_shapes_stamps.ptx
index 7e140ba..c2f2408 100644
--- a/pretext/Turtles/geometry_shapes_stamps.ptx
+++ b/pretext/Turtles/geometry_shapes_stamps.ptx
@@ -6,16 +6,16 @@
one of four default shapes, or a custom shape. C-Turtle features four default shapes, triangle,
indented_triangle, square, and arrow.
The following code example shows how to set the shape of a turtle by giving it the name of a shape.
-
+
turtle.shape("square");
-
+
Given that all primitive shapes are defined as a collection of points, all of the default shapes are also defined this way.
Polygons, for custom and default shapes, must have their points defined in counter-clockwise order to appear correctly.
This is due to the mathematics behind filling arbitrary shapes, and is a limitation almost all computer graphics need to
abide by. Consider the order of their points in the following table, and how they could be considered counter-clockwise.
They are in order from top to bottom, and one edge exists between the first last points for each of these shapes. Please note
that positive Y coordinates are lower on the screen, while negative Y coordinates are higher on the screen. Coordinates at
- the origin– that is, coordinate 0x, 0y– is at the point or tip of the turtle. This is why most of the default shapes
+ the origin– that is, coordinate 0x, 0y– is at the point or tip of the turtle. This is why most of the default shapes
have their first coordinate there.
@@ -145,18 +145,18 @@ turtle.shape("square");
Indented Triangle Definition
The example code below illustrates how to create your own shape. We use the Polygon class to represent our shape.
For this example, we take the triangle default shape and make every Y coordinate negative to make it appear upside-down.
-
+
ct::Polygon upside_down_triangle = {
{0, 0}, //First point
{-5, -5}, //Second point
{5, -5} //and so on.
};
-
+
The following code is a full example for setting your turtle to a custom shape. Feel free to mess around with
the coordinates of the polygon, you might surprise yourself with what shape you end up with!
Stamps provide a way to make several copies of the shape of the turtle across the screen without having to trace each
shape individually with the turtle. This can be used for a variety of visual effects, however it is often used as a
@@ -188,7 +188,7 @@ int main(){
The following code is a full example showing how to combine custom shapes with stamp placement.
C++ is designed with the principal that speed is more important than safety and error-checking.
+
+
C++ is designed with the principle that speed is more important than safety and error-checking.
This differs from languages like Python, which is considerably more restrictive in regards to
aspects such as memory allocations and resource management. C++ is translated to machine language
when it is compiled, which is a step skipped by Python. Python skips this step in favor of immediate
@@ -12,7 +13,8 @@
allows C++ to communicate better with other components of your computer, such as your graphics processing unit, or GPU.
This is one of many reasons C++ is considered an industry standard for high-performance graphics applications, such as
video games or software used for visual effects in movies.
-
+
+What are Turtles?
Turtle graphics are a popular and simple way for introducing programming to beginners.
It was part of the original Logo programming language developed by
@@ -44,7 +46,7 @@
the same thing. Try running both and comparing how the code looks between the two versions.
-
+
\ No newline at end of file
diff --git a/pretext/Turtles/pattern_application.ptx b/pretext/Turtles/pattern_application.ptx
index fe22a8c..ad230ac 100644
--- a/pretext/Turtles/pattern_application.ptx
+++ b/pretext/Turtles/pattern_application.ptx
@@ -7,7 +7,7 @@
without any gaps in between them. This art form is known today as tessellation,
which can be observed in any modern building that is composed of bricks,
or any floor covered in ceramic tiles. Mosaics are defined by their interlocking shapes,
- however, what these shapes are made of‒ or, the medium‒ varies depending on the artist.
+ however, what these shapes are made of‒ or, the medium‒ varies depending on the artist.
The common mediums for this art form have changed over time,
ranging from pieces of clay to pieces of wood. More recently,
digital mediums have been used as an effective alternative to physical materials.
@@ -17,7 +17,7 @@
You must create a similar image with the following criteria:
@@ -119,7 +119,7 @@ wn.tracer(1)
-
+
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -133,7 +133,6 @@ int main() {
scr.bye();
return 0;
}
-
+
-
-
+
\ No newline at end of file
diff --git a/pretext/Turtles/summary.ptx b/pretext/Turtles/summary.ptx
index c42c23a..0958d29 100644
--- a/pretext/Turtles/summary.ptx
+++ b/pretext/Turtles/summary.ptx
@@ -26,22 +26,24 @@
-
+
Match every turtle function name with the description of what it does.
+
Feedback shows incorrect matches.
- what color to fill drawing with.turtle.fillcolorwrite some text to the canvas.turtle.writestart filling the shape.turtle.beginfillstops filling the shape.turtle.endfillchange the paintbrush color.turtle.pencolor
+ what color to fill drawing with.turtle.fillcolorwrite some text to the canvas.turtle.writestart filling the shape.turtle.beginfillstops filling the shape.turtle.endfillchange the paintbrush color.turtle.pencolor
-
+
Match every turtle function name with the description of what it does.
-
- change the speedturtle.speedmove backward.turtle.backmove forward.turtle.forwardmove to a specific coordinate.turtle.goto
- change the paintbrush size.turtle.width
-
+
Feedback shows incorrect matches.
+
+ change the speedturtle.speedmove backward.turtle.backmove forward.turtle.forwardmove to a specific coordinate.turtle.goto
+ change the paintbrush size.turtle.width
+
Turtles must exist on a TurtleScreen to be used. This is a significant difference from
Python, as you are required to create your own screen before creating a Turtle object.
-
+
ct::TurtleScreen screen;
ct::Turtle turtle(screen);
//Notice how the Screen is given to our Turtle when we create it.
-
+
Closing a TurtleScreen works exactly how it does in Python. For this chapter, only bye is used.
Calling it is not completely necessary, as it is also called automatically if it, or an equivalent method, hasn't been called.
When working outside of the textbook, the exitonclick method is also available.
-
+
screen.bye();
-
+
Turtles are based on the following premise: There is a turtle on a canvas with a colored pen
attached to their tail. In this case, the canvas is a TurtleScreen. This Turtle will
follow any command you give it, which consist of telling it to go certain directions, what color
@@ -232,7 +232,7 @@ screen.bye();
The expected output would be a purple square in the center of the turtle's canvas.
If you have experience with Turtles in Python, a lot of what you see in the example should look
@@ -319,17 +319,18 @@ int main() {
Match the turtle method descriptions to the methods they belong to.
+
Feedback shows incorrect matches.
-turn to the left.turtle.leftchange the speedturtle.speedturn to the right.turtle.rightpick pen up.turtle.penupput pen down.turtle.pendown
+turn to the left.turtle.leftchange the speedturtle.speedturn to the right.turtle.rightpick pen up.turtle.penupput pen down.turtle.pendown
Match the turtle method descriptions to the methods they belong to.
-
- what color to fill drawing with.turtle.fillcolorstart filling the shape.turtle.beginfillstops filling the shape.turtle.endfillchange the pen color.turtle.pencolorchange the pen size.turtle.width
-
+
Feedback shows incorrect matches.
+
+ what color to fill drawing with.turtle.fillcolorstart filling the shape.turtle.beginfillstops filling the shape.turtle.endfillchange the pen color.turtle.pencolorchange the pen size.turtle.width
+
-
-
+
\ No newline at end of file
diff --git a/pretext/assignments.ptx b/pretext/assignments.ptx
index b3b1b24..4c04478 100644
--- a/pretext/assignments.ptx
+++ b/pretext/assignments.ptx
@@ -7,8 +7,8 @@
you can do this:
Write a program that counts from 1 to 10
-
+
# your code here
-
+
-
+
\ No newline at end of file
diff --git a/pretext/cpp4python.ptx b/pretext/main.ptx
similarity index 81%
rename from pretext/cpp4python.ptx
rename to pretext/main.ptx
index eb0377d..fd52e52 100644
--- a/pretext/cpp4python.ptx
+++ b/pretext/main.ptx
@@ -3,8 +3,10 @@
+
C++ for Python Programmers
- The PreTeXt Edition
+
+
@@ -13,5 +15,7 @@
+
+
\ No newline at end of file
diff --git a/pretext/meta_backmatter.ptx b/pretext/meta_backmatter.ptx
new file mode 100644
index 0000000..5afca2f
--- /dev/null
+++ b/pretext/meta_backmatter.ptx
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+ Appendices
+
+
+
+
+
+ Symbols Index
+
+
+
+
+ Text Index
+
+
+
+
+
+ This book was authored in .
+
+
+
+
diff --git a/pretext/meta_frontmatter.ptx b/pretext/meta_frontmatter.ptx
new file mode 100644
index 0000000..d352c34
--- /dev/null
+++ b/pretext/meta_frontmatter.ptx
@@ -0,0 +1,68 @@
+
+
+
+
+
+
+
+ Dr. Jan Pearce and Dr. Brad Miller
+ Computer Science
+ Berea College
+
+
+
+
+
+
+ 20182026
+ Dr. Jan Pearce
+
+
+
+ CC BY-SA 4.0
+
+
+
+
+ This work is licensed under the open source Creative Commons Attribution-ShareAlike 4.0 International License. To view a copy of this license, visit
+
+ CC BY-SA 4.0
+
+ For a human readable summary see CC-BY-SA 4.0 Summary.
+
+
+
+
+
+
+
+
+
+ Open Source Licensing
+
+
+
+
+
+
+ Special acknowledgement is due to Jesse Walker-Schadler who while just a student in the Berea College Data Structures course had a vision of making graphics in C++ as easy as they are in Python both in terms of both syntax and installations. Over the course of two summers, he realized this vision with the creation in the open source CTurtle library which provides all of the C++ interactive graphics in this textbook.
+
+
+
+
+
+
+
+ This short ebook is intended to make it easy for anyone with at least some background in Python to transition to programming in C++.
+
+
+ Portions of this book began as Java for Python Programmers by Brad Miller. These sections were translated to C++ by Jan Pearce and a team of excellent Berea College students in 2018 and early 2019. Other portions of this book began as web pages written by Jan Pearce as support for a Berea College C++ programming class. Still other sections were newly written by Jan Pearce for this ebook.
+
+
+
+
diff --git a/project.ptx b/project.ptx
index d96d920..e4a1f7b 100644
--- a/project.ptx
+++ b/project.ptx
@@ -1,64 +1,32 @@
-
+
-
- html
- pretext/cpp4python.ptx
- pretext/publication-rs-for-all.xml
- output/html
-
-
- html
- pretext/cpp4python.ptx
- pretext/publication-rs-academy.xml
- published/cpp4py-v2
-
-
- epub
- pretext/cpp4python.ptx
- pretext/publication-pub.xml
- published/epub
-
-
- latex
- pretext/cpp4python.ptx
- pretext/publication-rs-for-all.xml
- output/latex
-
-
- pdf
- pretext/cpp4python.ptx
- pretext/publication-rs-for-all.xml
- output/pdf
-
-
- html
- source/cpp4python.ptx
- publication/publication.ptx
- output/subset
-
-
- ch-first
-
+
+
+
+
+
+
+
+
+
-
- latex
- pdflatex
- xelatex
- pdf2svg
- asy
- sage
- convert
- pdftops
- pdf-crop-margins
- pageres
- node
- file2brl
-
-
+
\ No newline at end of file
diff --git a/pretext/publication-rs-for-all.xml b/publication/publication.ptx
similarity index 95%
rename from pretext/publication-rs-for-all.xml
rename to publication/publication.ptx
index f709a8c..1833aae 100644
--- a/pretext/publication-rs-for-all.xml
+++ b/publication/publication.ptx
@@ -29,7 +29,7 @@ along with PreTeXt. If not, see .
-
+
diff --git a/pretext/publication-rs-academy.xml b/publication/runestone.ptx
similarity index 100%
rename from pretext/publication-rs-academy.xml
rename to publication/runestone.ptx
diff --git a/requirements.txt b/requirements.txt
index c01ba91..834f79c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,4 @@
-runestone>=7.0.0
+runestone>=3.2.11
SQLAlchemy>=1.0.8
-pretext>=1.6.0
\ No newline at end of file
+jupyterlite-sphinx
+pretext=2.18.0
\ No newline at end of file