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 Boolean data types are named after George Boole who was an English mathematician,
+ Boolean C++ uses the standard Boolean operators, but they are represented
- differently than in Python: Boolean data objects are also used as results for comparison operators
- such as equality (==) and greater than ( When a C++ variable is declared, space in memory is set aside to hold
@@ -213,7 +213,7 @@ main()
Consider the following session: The declaration
+ Rearrange the blocks to create a C++ function In Python strings can be created with single or double quotes.
- In C++ single quotes are used for the character ( Consider the following code. Try the following question.Boolean
should be capitalized. However,
- the Boolean data type, in C++ uses the keyword and
is given by or
is given by and
is given by or
is given by not
is given by
#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()
-
+
#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()
-
+
#include <iostream>
using namespace std;
@@ -236,7 +236,7 @@ int main(){
return 0;
}
-
+
# 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;
}
-
+
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 C++ data types include
Numeric C++ data types include
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
Exponentiation in C++ is done using
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 e2b3a70..75cb472 100644
--- a/pretext/AtomicData/Pointers.ptx
+++ b/pretext/AtomicData/Pointers.ptx
@@ -1,6 +1,6 @@
A C++ A C++ 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
#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
SOMETYPE *variablename; // preferable SOMETYPE * variablename; @@ -102,7 +102,7 @@ SOMETYPE* variablename;
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 syntax is shown below, where varN stores the value, and ptrN stores @@ -117,13 +117,13 @@ int *ptrN; ptrN = &varN;
The results of running this C++ code will look like the diagram below.
-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.
+ toIn 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.
@@ -167,7 +167,7 @@ int main( ) {- + #include <iostream> using namespace std; @@ -148,7 +148,7 @@ int main( ) { return 0; } - +
- + #include <iostream> using namespace std; @@ -185,7 +185,7 @@ int main( ) { return 0; } - +
If your compiler does not catch that error (the one for this class may),
the first
After changing *ptrN, varN now has: 50+
varN value: 100
which is expected because you changed where ptrN is pointing to and NOT the contents of where it is pointing.
The second segmentation fault
. Although such an error message looks bad,
+ about a segmentation fault
seg fault
is in fact a helpful error because unlike the elusive logical
errors, the reason is fairly localized.
Like
Like
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
- + #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! varPntr: 50 pntrN: 50 Right! varPntr: 150 pntrN: 150 No, the values do not add together! All variables must be declared before use in C++. 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.
+
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++
NOTE: A C++
--+
- -
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 allocated dynamically allocated in 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
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?
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
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
The speed and low-level control that arrays offer us
- as programmers is powerful… and dangerous.
+ as programmers is powerful
// 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
#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()
-
+
In addition to the numeric, Boolean, and character types,
C++ also offers built-in collection types.
- A
Arrays, vectors, strings, sets, and hash tables are among these useful
diff --git a/pretext/CollectionData/HashTables.ptx b/pretext/CollectionData/HashTables.ptx
index a6efbe4..87a1a90 100644
--- a/pretext/CollectionData/HashTables.ptx
+++ b/pretext/CollectionData/HashTables.ptx
@@ -1,18 +1,18 @@
If you have used a Python dictionary, then you have used a hash table.
- A Each hash table has a hash function which
+ Each hash table has a In Python, the dictionary data type represents the implementation of the hash table.
- In C++, the unordered_map implements the hash table, and the The syntax for hash table access is much like we might expect
@@ -24,9 +24,9 @@
It is important to note that hash tables are organized by the location given
@@ -81,9 +81,9 @@ main()
Hash Tables have both methods and operators. Match the Hash Table operations with their corresponding explination. Feedback shows incorrect matches. 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 Check your understanding by completing the following question. Match the String operations with their corresponding explanation. Feedback shows incorrect matches. Match the String operation with their corresponding explanation. Feedback shows incorrect matches. Drag each data type to its' corresponding C++ initialization syntax. Feedback shows incorrect matches. An An 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.
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. Unordered sets support a number of methods that should be familiar to those who
have worked with sets in a mathematics setting. The code below is an example of a program that can detect if a specific char is in an unordered set. the Match the Unordered Sets operations with their corresponding explination. Feedback shows incorrect matches. A very common programming task is to grow a vector using the When iterating vectors, you must first find the length of your container. You can simply call the An optional secondary version of the In the above example, the use of Remembering that C++ is designed for speed, not protection,
we will likely not be surprised by the following: Match the Vector operations with their corresponding explination. Feedback shows incorrect matches. Match the Vector operations with their corresponding explination. Feedback shows incorrect matches.
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. Feedback shows incorrect matches. Match the words to thier corresponding definition. Feedback shows incorrect matches. Match the words to thier corresponding definition. Feedback shows incorrect matches. Conditional statements in Python and C++ are very similar. In C++ we have a couple of ways to write this We can get closer to the look of the elif statement in C++ by
+ We can get closer to the look of the elif C++ also supports a C++ also supports a To write the grade
program using a switch statement we would use the following: Frankly, the Even though the In the example above, the A common use of the The code will use Like Python C++ also supports the Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. For repeating a block of code, C++ provides a standard The 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 @@
There are two types of errors that typically occur when writing
- programs. The first, known as a The other type of error, known as a The other type of error, known as a 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 When an exception occurs, we say that it has This will catch the fact that an exception is raised by It is also possible for a programmer to use nested try and except statements,
+ It is also possible for a programmer to use nested 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 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. There are two types of errors that occur while writing programs: syntax errors and logic errors Click on the syntax error. Remember, syntax errors occur more for people learning a new language. 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? Match the words with their corresponding definition. Feedback shows incorrect matches. 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 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 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: 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 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 The syntax for this function definition includes the name, The We could go a step further and implement our own square root function by using a well-known
technique called In C++ programming, two or more functions can have same
name when they can be distinguished by the parameters.
@@ -14,7 +14,7 @@
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... 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. In all of the functions we have written thus far, we have used a function calling
- mechanism called Notice what happens when 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 For this program For this program Analyze the program and answer the question that involves parameter passing below:
Like Python, C++ supports the use of functions. Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. This function returns The following example code fragment safely quits the program entirely in case an I/O operation fails: After opening the After opening the For more on Error Handling, see section 1.11. The number of characters for a c-string must be one greater than the number of actual characters! Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function Once connected, the program can read from that file. Pictorially, this is what happens: the the Pictorally, we get a stream of data flowing out of the program: Because out_stream is an object of type To disconnect the To disconnect the To close the file for Answer the question below concerning the use of the Answer the question below concerning the use of the A function that is associated with a certain type of object is called a A function that is associated with a certain type of object is called a 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. File handling in C++ uses Drag the corresponding library to what you would use it for. Which library is used for which task? Match the words to thier corresponding definition. Feedback shows incorrect matches. 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 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 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 This is the The input file Now, lets look at a more Next, lets look at the same program written in C++: The above program can alternatively be written as follows to allow
better facilitate standard input and output: What we see is that at the core there are a few similarities with the
complicated Python version, such as the A question you may have about this little program is 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 Preprocessor directives in C++ appear as statements preceded by the hash sign
+ You can think of the You can think of the There are two ways to use Here the angle-brackets Here the angle-brackets Unlike Python, every C++ program The The C++ functions and other C++ code blocks are grouped together using the curly C++ functions and other C++ code blocks are grouped together using the curly In fact, the following program will run perfectly
even though the lack of meaningful spacing is more difficult for humans to read. 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;}
Python and C++ both support comments that are not processed by the interpreter or compiler. Python's single line comment begins with a hash ( Python supports comments using triple quotes.
Like Python, C++ also supports multi-line comments
beginning with
+ A In addition to being able to output to the standard output, we want to be able to take input from the user.
The command Here is an example that uses In this example, you may note the line Match Compiler and Interpreter to the correct definition. This is feedback. 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:
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. // @ none of the above False none of the above 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. Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. Drag each glossary term to its' corresponding definition. Feedback shows incorrect matches. Regarding angles, Turtles can use both degrees and radians for their rotations. You can choose between the two using the
The This can be combined with the 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
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 @@
Unlike in Python, the The following code example shows how to set the shape of a turtle by giving it the name of a shape. 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 The example code below illustrates how to create your own shape. We use the 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 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. 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 @@
Consider the following examples. You must create a similar image with the following criteria:
+ Match every turtle function name with the description of what it does.
Feedback shows incorrect matches.
+ Match every turtle function name with the description of what it does.
Feedback shows incorrect matches. Turtles must exist on a Closing a Turtles are based on the following premise: Consider the following annotated example. 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. Match the turtle method descriptions to the methods they belong to. Feedback shows incorrect matches. Write a program that counts from 1 to 10
+ This book was authored in
+
+ Special acknowledgement is due to
+ 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.
+ 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, #include <unordered_map>
+// 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()
-
+
+// 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,14 +121,18 @@ def main():
print(spnumbers[key])
main()
-
+
+
+
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
// 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()
-
+
set<int> mySet = {3, 6, 4, 78, 10}
+ unordered_set<int> mySet = {3, 6, 4, 78, 10};
// 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;
}
-
+
#include <iostream>
using namespace std;
@@ -175,7 +175,7 @@ int main() {
return 0;
}
-
+
// 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()
-
+
// 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;
}
-
+
// 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()
-
+
+
# demonstrates if,elif, and else statements in python
def main():
grade = 85
@@ -66,12 +67,12 @@ def main():
print('A')
main()
-
+
// Shows how to use conditional statements
#include <iostream>
using namespace std;
@@ -104,16 +105,16 @@ main()
}
return 0;
}
-
+
//Shows how to put conditional statements together,
//specfically putting "else if" after an "if" statement.
#include <iostream>
@@ -139,7 +140,7 @@ main()
return 0;
}
-
+
// Shows how to use a Switch statement.
#include <iostream>
@@ -189,20 +190,20 @@ main()
return 0;
}
-
+
#include <iostream>
using namespace std;
@@ -15,14 +16,14 @@ int main() {
cout << i << "hello world" << endl;
}
}
-
+
#include <iostream>
using namespace std;
@@ -35,7 +36,7 @@ using namespace std;
return 0;
}
-
+
+
int counter = 1;
while (counter <= 5) { /*Use of an interactive method until the
the loop ends */
@@ -24,7 +24,7 @@ Hello, world
condition is while ((counter <= 10) && (!done)) {
...
thrown.
You can
- catch
the exception that has been raised by using a catch
// 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;
}
-
+
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() {
+
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];
};}
- 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;
}
-
+
inside the box,
simply compute the result of
#include <iostream>
using namespace std;
@@ -63,13 +63,13 @@ int main() {
return 0;
}
-
+
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
// 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 returns the output number of steps walked
#include <iostream>
using namespace std;
@@ -132,7 +131,7 @@ int main() {
return 0;
}
-
+
// 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()
-
+
nextVar = 20 inputVar = 4
myVar = 10
@@ -39,7 +39,7 @@ void callingFunction() { /*return type void which indicates
-
#include <iostream>
using namespace std;
@@ -81,14 +81,14 @@ int main( ) {
return 0;
}
-
+
&
‘s in this code to see what happens.&
‘s in this code to see what happens.
// demonstrates the difference between pass-by-value
// and pass-by-reference functions.
#include <iostream>
@@ -121,7 +121,7 @@ int main(){
return 0;
}
-
+
+
in_stream.fail();
myFile.txt
file, the 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;
+ }
+
+ myFile.txt
file, the 1
versus a 0
, indicating an Error has occurred.myFileName.dat
- can be stored in an array of chars called a // Syntax: char C-string_name[LEN];
// Example:
char filename[16];
@@ -23,7 +23,7 @@ char filename[16];
+
myFile.txt
, assuming a file named that exists in the current directory, and connect myFile.txt
, assuming a file named that exists in the current directory, and connect in_stream.open("myFile.txt");
out_stream.open("anotherFile.txt");
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.in_stream.close();
out_stream.close();
- // 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 @@
#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;
-}
+
// 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.
+
+ 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
+
+
+
+
+ // 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 Pearce10 -20 30 -40
500 300 -100 1000
@@ -109,9 +114,7 @@ void make_neat(
-20.00000
+30.00000
-40.00000
- neat.dat
to output the results.
print("Hello World!")
-
+
complicated
version of the hello world
program with a
def main():
print("Hello World!")
main()
-
+
#include <iostream>
int main(){
@@ -32,13 +32,13 @@ int main(){
std::cout << "Hello World!\n";
return 0;
}
-
+
#include <iostream>
using namespace std;
@@ -46,7 +46,7 @@ int main(){
cout << "Hello World!\n";
return 0;
}
-
+
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 language #include <libraryname>
#include "filename"
-
#include <iostream>
using namespace std; int main(){cout << "Hello World!\n"; return 0;}
-
+
sink
.)
- Output streams send data out, and the standard output stream character output
.
Much like the Python output operator
.
+ When output operator
+
can be used to concatenate in Python.
/* Ever heard of rubber duck debugging?
See https://en.wikipedia.org/wiki/Rubber_duck_debugging */
#include <iostream>
@@ -212,7 +216,7 @@ int main(){
cout << " ( .__> /" << endl;
cout << " `----' " << endl;
}
-
+
character input
and it makes getting input from the standard input device (usually the keyboard) relatively easy.
- The input operator in C++ is character input
and it makes getting input from the standard input device (usually the keyboard) relatively easy.
+ The input operator
#include <iostream>
using namespace std;
@@ -250,14 +254,14 @@ int main() {
return 0;
}
-
+
/* 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.
}
-
+
+
turtle.degrees();
turtle.right(90);//90-degree turn to the right
turtle.radians();
turtle.left(1.5708f);//Equivalent rotation in radians to the left.
-
screen.tracer(12);
//Show one out of every 12 frames of animation.
-
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.
-
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -105,7 +105,7 @@ int main(){
return 0;
}
-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"});
-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,
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);
-
turtle.shape("square");
-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.
ct::Polygon upside_down_triangle = {
{0, 0}, //First point
{-5, -5}, //Second point
{5, -5} //and so on.
};
-
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -177,7 +177,7 @@ int main(){
screen.bye();
return 0;
}
-
+
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -224,7 +224,7 @@ int main(){
screen.bye();
return 0;
}
-
+
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.
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -62,11 +64,11 @@ int main() {
scr.bye();
return 0;
}
-
+
import turtle
turt = turtle.Turtle()
@@ -78,7 +80,7 @@ for i in range(4):
turt.forward(50)
turt.right(90)
turt.end_fill()
-
+
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -62,11 +62,11 @@ int main() {
scr.bye();
return 0;
}
-
+
import turtle
SQUARE_SIZE = 35
@@ -106,7 +106,7 @@ for i in range(8):
else:
b=0
wn.tracer(1)
-
+
@@ -119,7 +119,7 @@ wn.tracer(1)
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -133,7 +133,6 @@ int main() {
scr.bye();
return 0;
}
-
+
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -61,7 +63,7 @@ int main() {
scr.bye();
return 0;
}
-
+
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -126,7 +128,7 @@ int main() {
scr.bye();
return 0;
}
-
ct::TurtleScreen screen;
ct::Turtle turtle(screen);
//Notice how the Screen is given to our Turtle when we create it.
-
screen.bye();
-There is a turtle on a canvas with a colored pen
attached to their tail.
In this case, the canvas is a
#include <CTurtle.hpp>
namespace ct = cturtle;
@@ -270,7 +270,7 @@ int main() {
screen.bye();
return 0;
}
-
+
# your code here
-
+