diff --git a/.gitignore b/.gitignore
index d00113f..27f2579 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,134 @@
-# Ignore the following:
+# Boilerplate list of files in a PreTeXt project for git to ignore
+# ensure this file is tracked
+!.gitignore
+
+# don't track the .cache directory
+.cache/*
+
+# don't track unpublished builds or stage
+output
+
+# don't track assets generated from source
+generated-assets
+
+# don't track the executables.ptx file
+executables.ptx
+
+# don't track node packages
+node_modules
+
+# don't track error logs
+.error_schema.log
+cli.log
+**/cli.log
+logs
+
+# don't track OS related files (windows/macos/linux)
+.DS_Store
+.DS_Store?
+._*
+.AppleDouble
+.LSOverride
+.Spotlight-V100
+.Trashes
+Icon
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+Thumbs.db
+Thumbs.db:encryptable
+ehthumbs.db
+ehthumbs_vista.db
+*.stackdump
+*.lnk
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+[Dd]esktop.ini
+.directory
+.fuse_hidden*
+.Trash-*
+.nfs*
+.idea/*
+
+# Don't include VSCode generated files
+.vscode
+*.code-workspace
+
+# Don't inlucde SublimeText files
+# Cache files for Sublime Text
+*.tmlanguage.cache
+*.tmPreferences.cache
+*.stTheme.cache
+
+# Workspace files are user-specific
+*.sublime-workspace
+
+# Project files should be checked into the repository, unless a significant
+# proportion of contributors will probably not be using Sublime Text
+*.sublime-project
+
+# SFTP configuration file
+sftp-config.json
+sftp-config-alt*.json
+
+# Package control specific files
+Package Control.last-run
+Package Control.ca-list
+Package Control.ca-bundle
+Package Control.system-ca-bundle
+Package Control.cache/
+Package Control.ca-certs/
+Package Control.merged-ca-bundle
+Package Control.user-ca-bundle
+oscrypto-ca-bundle.crt
+bh_unicode_properties.cache
+
+# Sublime-github package stores a github token in this file
+# https://packagecontrol.io/packages/sublime-github
+GitHub.sublime-settings
+
+
+# Don't include Dropbox settings and caches
+.dropbox
+.dropbox.attr
+.dropbox.cache
+
+# Additionals based upon Pretextbook .gitignore
+user/*
+
+script/mjsre/node_modules/
+script/mjsre/package-lock.json
+pretext/__pycache__/**
+
+# any file ending in ~ (backups, usually)
+*~
+
build_info
-*.pyc
-__pycache__/
+**/_build
+**/rsbuild
+**/build
build/*
published
-.idea/*
-source/doctrees/*
-*~
+
+# Codespaces set-up
+.devcontainer.json
+
+# ignore temp files
+temp-*
+
+# Ignore the following (from runestone .gitignore):
+
+*.pyc
+__pycache__/
+
sphinx-enki-info.txt
sphinx_settings.json
pavement.py
+
+# Don't track codechat config (will be generated automatically)
+codechat_config.yaml
diff --git a/README.rst b/README.rst
index 9fdc4e5..f41d20d 100644
--- a/README.rst
+++ b/README.rst
@@ -3,34 +3,22 @@ C++ for Python Programmers
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.
-We are very grateful to Berea College student Jesse Walker-Schadler.
- In the summer of 2019 Jesse wrote an excellent wrapper
-for the CImg library that would allow graphics in C++ to utilize commands like
-the Turtle library in Python. In the summer of 2020 he led the incorporation into
-this book.
-
-We are also particularly grateful to Runestone for the excellent framework for
-ebooks that facilitate running both C++ and Python in the browser.
-
-Getting Started
-===============
-
-We have tried to make it as easy as possible for you to build and use this book.
-
-1. You can see and read this book online at
- `interactivepython.org C++ requires the users specify the specific data type of each variable
+ before it is used.
+ The primary C++ built-in atomic data types are: integer ( 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 (==) When a C++ variable is declared, space in memory is set aside to hold
+ this type of value.
+ A C++ variable can optionally be initialized in the declaration by
+ using a combination of a declaration and an assignment statement. Consider the following session: The declaration Why did theBool output a value of 1 after being set to 4? Setting theBool to anything other than true or false is ignored. No. Try changing the code and setting theBool to 0. Setting theBool to anything > 0 will be true and false otherwise. No. Try changing the code and setting theBool to -4. false == 0 and true = !false i.e. anything that is not zero and can be converted to a Boolean is not false, thus it must be true. Correct! None of the above. Try again. One of the above is correct. You might try changing the code and rerunning.
+ 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. If I want to create a string in C++, what set of symbols may be used? ' ' No, single quotes are only used for single characters. " " Good job reading! ' ' or " " may be used No. Only one set of symbols may be used. It depends upon the implementation. No. The implementation is consistent. none of the above One of the above is indeed correct. 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. Q-3: If I want to create a string in C++, what set of symbols may be used? ' ' No, single quotes are only used for single characters. " " Good job reading! ' ' or " " may be used No. Only one set of symbols may be used. It depends upon the implementation. No. The implementation is consistent. none of the above One of the above is indeed correct. Q-20: If I want to use the ' ' Right! " " No. Double quotes are only used for strings. ' ' or " " may be used No. Only one set of symbols may be used. It depends upon the implementation. No. The implementation is consistent. none of the above One of the above is indeed correct. Q-21: A/an Right! Be more specific! That’s Python, not C++! Incorrect. Please try again Q-22: How may one reference a variable’s memory address in C++? using ``&`` Right! ``&`` is the "address-of" operator, used to reference an address. using ``*`` No. ``int *p;`` defines a pointer to an integer, and ``*p`` would dereference that pointer, i.e. retrieve the data that p points to. using ``id`` No. This is used in Python. It depends upon the implementation. No. Try again. none of the above One of the above is indeed correct. 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. In Python we can use Exponentiation in C++ is done using Run the following code to see that you understand each result. When declaring numeric variables in C++,
+ modifiers like what is the result of dividing 1 Right! This is like ``3//2`` in Python. 1.5 No. Integer division is used. Try again. 2 No. Integer division is used. Try again. A run-time error will occur. No, C++ generally will try to do as you ask. none of the above One of the above is correct. How do I raise 4 to 5th power in C++? ``4**5`` No, ``**`` is used in Python, not C++. ``5**4`` No, ``**`` is used in Python, not C++, and the operators are reversed. ``4^5`` No. The ``^`` is a valid operator in C++, but it does something else. ``pow(4, 5)`` You got it! Remember the cmath library will need to be included for pow() to work. 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
+ computer program. Let's look at some examples of storing an integer in Python and C++. In Python every single thing is stored as an object.
+ Hence, a Python variable is actually a reference to an object that is stored in memory.
+ Hence, each Python variable requires two memory locations:
+ one to store the reference, and the other to store the variable value itself in an object. In C++ the value of each variable is stored directly in memory without the need
+ for either a reference or an object. This makes access faster, but it is one of
+ the reasons we need to declare each variable because different types take differing
+ amounts of space in memory! The following code declares a variable called varN that has in it a
+ value of 100: In C++ the results of running this code will look like the diagram below: In each case, when we want to output the value to the console, we use the variable name
+ to do so. But, we can also identify the memory location of the variable by its address.
+ In both Python and C++, this address
+ may change each time the program is run. In C++, the address will always look
+ odd because it will be the actual memory address written in a hexadecimal code
+ which is a base 16 code like 0x7ffd93f25244.
+ In Python it is implementation dependent,
+ it is sometimes a hexadecimal code and sometimes just a count or another
+ way to reference the address. In Python we use In both Python and C++, variables are stored in memory locations which are dependent
+ upon the run itself. If you repeatedly run the above code in either C++ or Python, you may
+ see the location change. As suggested above, in Python, it is impossible to store a variable directly.
+ Instead, we must use a variable name and a reference to the data object.
+ (Hence the arrow in the image.)
+ In C++, variables store values directly, because they are faster to reference. References are slower, but they are sometimes useful.
+ If in C++, we want to create a analogous reference to a memory location,
+ we must use a special data type called a When declaring a pointer in C++ that will White space in C++ generally does not matter, so the following pointer declarations However, the first declaration is preferable because it is clearer to the
+ programmer that the variable is in fact a pointer because the asterisk is closer
+ to the variable name. 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
+ the address of where varN is located: Keep in mind that when declaring a C++ pointer, the pointer needs to
+ reference the same type as the variable or constant to which it points. Expanding on the example above where varN has the value of 9. 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 Let's extend the example above to output the value of a variable and its address
+ in memory: Compiling and running the above code will have the program output the
+ value in varN,
+ what is in ptrN (the memory address of varN),
+ and what value is located at that
+ memory location. The second output sentence is the address of varN, which would most likely be
+ different if you run the program on your machine. WARNING: What happens if you forget the ampersand
+ when assigning a value to a pointer
+ and have the following instructions instead? If your compiler does not catch that error (the one for this class may),
+ the first which is expected because you changed where ptrN is pointing to and
+ NOT the contents of where it is pointing. The second Like The following example demonstrates how the null pointer works.
+ 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
+ Helpful Tip: The null pointer becomes very useful when you must test
+ the state of a pointer, such as whether the assignment to an address
+ is valid or not. If the lines (varN = 50;) and (cout << "ptrN: " << *ptrN << endl;) were inserted between lines 7 and 8, what would it cout? pntrN: 100 Not quite, the variable varN no longer equals 100 past line 7! pntrN: 50 Right! pntrN: 150 No, the values do not add together! 0x7ffeb9ce053c We are dereferencing the pointer, so you would not get the address of varN. Try again! none of the above One of the above is indeed correct. All variables must be declared before use in C++. C++ has typical built-in numeric types: C++ has the Boolean type The character data type Pointers are a type of variable that stores a memory address. To declare a pointer, an Boolean
should be capitalized. However,
+ the Boolean data type, in C++ uses the keyword and
is given by or
is given by not
is given by
+#include <iostream>
+using namespace std;
+
+// function that demonstrates logical operators
+int main() {
+ cout << true << endl;
+ cout << false << endl;
+ cout << (true || false) << endl;
+ cout << (true && false) << endl;
+ return 0;
+}
+
+
+# Function that demonstrates logical operators.
+def main():
+ print(True)
+ print(False)
+ print(True or False)
+ print(True and False)
+main()
+
+
+
+#include <iostream>
+using namespace std;
+
+// function that demonstrates relational operators.
+int main(){
+
+ cout << (5 == 10) << endl;
+ cout << (10 > 5) << endl;
+ cout << ((5 >= 1) && (5 <= 10)) << endl;
+
+ return 0;
+}
+
+
+# Function that demonstrates relational operators.
+def main():
+
+ print(5 == 10)
+ print(10 > 5)
+ print((5 >= 1) and (5 <= 10))
+
+main()
+
+
+#include <iostream>
+using namespace std;
+
+// Demonstrates how to use variables in C++
+// moreover, we assign an integer to a boolean variable,
+// showing the static typing of C++.
+int main(){
+
+ int theSum = 4;
+ cout << theSum << endl;
+
+ theSum = theSum + 1;
+ cout << theSum << endl;
+
+ bool theBool = true;
+ cout << theBool << endl;
+
+ theBool = 4;
+ cout << theBool << endl;
+
+ return 0;
+}
+
+ assigned
to the variable named on the left-hand side.
+ Here the type of the variable is integer.
+ Because Python is dynamically typed, if the type of the data
+ changes in the program, so does the type of the variable.
+ However, in C++, the data type cannot change.
+ This is a characteristic of C++'s static typing. A
+ variable can hold ever only one type of data.
+ Pitfall: C++ will often simply try to do the assignment you
+ requested without
+ complaining. Note what happened in the code above in the final output.
+# Shows direct comparison of both Strings & Characters in Python
+def main():
+
+ strvar = "b"
+ charvar = 'b'
+
+ print('b' == charvar)
+ print("b" == strvar)
+ print('a' == "a")
+
+main()
+
+
+#include <iostream>
+#include <string>
+using namespace std;
+
+// Demonstrates how chars and strings can not be
+// directly compared.
+int main(){
+
+ string strvar = "b";
+ char charvar = 'b';
+
+ cout << ('b' == charvar) << endl;
+ cout << ("b" == strvar) << endl;
+ //cout << ('a' == "a") << endl; // will error!
+
+ return 0;
+}
+
+
+# Shows direct comparison of both Strings & Characters in Python
+def main():
+
+ strvar = "b"
+ charvar = 'b'
+
+ print('b' == charvar)
+ print("b" == strvar)
+ print('a' == "a")
+
+main()
+
+
+#include <iostream>
+#include <string>
+using namespace std;
+
+// Demonstrates how chars and strings can not be
+// directly compared.
+int main(){
+
+ string strvar = "b";
+ char charvar = 'b';
+
+ cout << ('b' == charvar) << endl;
+ cout << ("b" == strvar) << endl;
+ //cout << ('a' == "a") << endl; // will error!
+
+ return 0;
+}
+
+
+#include <iostream>
+#include <cmath>
+using namespace std;
+
+// Function that perfoms various math operations
+int main(){
+
+ cout << (2+3*4) << endl;
+ cout << (2+3)*4 << endl;
+ cout << pow(2, 10) << endl;
+ cout << float(6)/3 << endl;
+ cout << float(7)/3 << endl;
+ cout << 7/3 << endl; //In C++ this is integer division
+ cout << 7%3 << endl;
+ cout << float(3)/6 << endl;
+ cout << 3/6 << endl;
+ cout << 3%6 << endl;
+ cout << pow(2, 100) << endl;
+
+ return 0;
+}
+
+
+# Function that performs a variety of math operations.
+def main():
+
+ print(2+3*4)
+ print((2+3)*4)
+ print(2**10)
+ print(6/3)
+ print(7/3)
+ print(7//3)
+ print(7%3)
+ print(3/6)
+ print(3//6)
+ print(3%6)
+ print(2**100)
+
+main()
+
+ // Python reference for a single integer value
+varN = 100
+
+ // C++ variable declaration and assignment of an integer value
+int varN = 100;
+
+#include <iostream>
+using namespace std;
+
+
+// outputs the value of a variable
+// as well as the memory address in C++.
+int main(){
+ int varN = 101;
+ cout << varN << endl;
+ cout << &varN << endl; //outputs the memory address of variable varN
+ return 0;
+}
+
+
+# Outputs the value & memory address of
+# variable titled varN.
+def main():
+ varN = 101;
+ print(varN)
+ print(id(varN)) # ID function returns the memory address in Python.
+
+main()
+
+ point
to the memory address of some
+ data type,
+ you will use the same rules of declaring variables and data types.
+ The key difference is that there must be an asterisk (*) between the data type and the
+ identifier.variableType *identifier; // syntax to declare a C++ pointer
+int *ptrx; // example of a C++ pointer to an integer
+ SOMETYPE *variablename; // preferable
+SOMETYPE * variablename;
+SOMETYPE* variablename;
+ variableType *ptrN = &varN; // a variable pointing to the address of varN
+ //variable declaration for a single integer value
+int varN = 9;
+int *ptrN;
+ptrN = &varN;
+ In other words, varN and *ptrN (note the asterisk in front!) reference the same
+value in the code above.
+
+
+
+
+
+
+#include <iostream>
+using namespace std;
+
+// demonstrates what happens when you dereference a pointer
+int main( ) {
+ int varN = 9;
+ int *ptrN = &varN; // ptrN points to varN address
+
+ cout << "varN value: " << varN << endl;
+ cout << "varN location: " << ptrN << endl;
+ cout << "dereference ptrN: " << *ptrN << endl;
+
+
+ return 0;
+}
+
+
+
+
+
+#include <iostream>
+using namespace std;
+
+int main( ) {
+ int varN = 100;
+ int *ptrN = varN; // Note no ampersand,
+ // ptrN now refers to memory position 100,
+ // whatever happens to be there!
+ // You might get an error or you might not!
+
+ cout << "varN value: " << varN << endl;
+ cout << "ptrN location: " << ptrN << endl;
+ cout << "ptrN points to varN: " << endl;
+ cout << "dereference ptrN: " << *ptrN << endl;
+
+ return 0;
+}
+
+ varN value: 100
+ segmentation fault
seg fault
is in fact a helpful error because unlike the elusive logical
+ errors, the reason is fairly localized.
+
+
+
+#include <iostream>
+using namespace std;
+
+//Shows the use of a Null pointer to represent "nothing".
+int main( ) {
+ int varN = 100;
+ int *pntrN = &varN;
+
+ while (pntrN) {
+ cout << "Pointer pntrN points to " << &pntrN << endl;
+ pntrN = nullptr;
+ }
+
+ cout << "Pointer pntrN points to nothing!\n";
+}
+
+
+
If I want to use the
' '
+Good job!
+ +" "
+No, double quotes are only used for string.
+ +' ' or " " may be used
+No. Only one set of symbols may be used.
+It depends upon the implementation.
+No. The implementation is consistent.
+none of the above
+One of the above is indeed correct.
+A/an is used to store a memory address in C++?
Right! Good job!
Be more specific!
That's Python, not C++!
Incorrect. Please try again.
How may one reference a variable’s memory address in C++?
+ +using ``&``
+Right! ``&`` is the "address-of" operator, used to reference an address.
+ +using ``*``
+No. ``int *p;`` defines a pointer to an integer, and ``*p`` would dereference that pointer, i.e. retrieve the data that p points to.
+ +using ``id``
+No. This is used in Python.
+It depends upon the implementation.
+No. Try again.
+none of the above
+One of the above is indeed correct.
+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.
C++ requires the users specify the specific data type of each variable
+ before it is used.
+ The primary C++ built-in atomic data types are: integer (
the address-of operator (
basic data type that cannot be broken down into any simpler data elements.
+ +keyword for Boolean data type.
+ +keyword for character data type that stores a single character.
+ +follow a pointer to its referenced memory location and read the data there.
+ +keyword for floating point data type.
+ +keyword for double-precision floating point data type.
+ +keyword for integer data type.
+ +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++
+++
+- +
++
statically allocated in which the array size is fixed at compile-time and cannot change- +
++
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
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.
+C++ arrays are similar to Python lists except that because C++ stores variables + directly, each element of a C++ array must be of identical data type. + Like Python lists, the indices for arrays start counting with 0.
+The use of arrays permits us to utilize an ordered set + 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
Statically allocated C++ arrays must be declared with both a type and a size at compile-time.
+double darray[4]; +int iarray[10]; +char arr2[3000];+
It is also possible to initialize statically allocated arrays at compile time, + in which case the number of items determines the array's size.
+int arr[] = {1, 2, 3, 4}; // This is size 4.
+char arr2[] = {'a', 'b', 'c'}; // This is size 3.
+string arr3[] = {"this", "is", "an", "array"}; // This is size 4.
+ Note that an array with a single element is not the same type as the
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
Here are examples of iteration.
+
+// outputs all elements in the array
+//to the console
+#include <iostream>
+using namespace std;
+
+int main(){
+ int myarray[] = {2,4,6,8};
+ for (int i=0; i<4; i++){
+ cout << myarray[i] << endl;
+ }
+ return 0;
+}
+
+
+"""Demonstrates how python protects from
+iterating past the end of a list"""
+
+def main():
+ mylist = [2, 4, 6, 8]
+ for i in range(8):
+ print(mylist[i])
+
+main()
+
+ The protections Python offers, however, takes time and C++ is designed for speed. + Python would never let you iterate beyond the end of + a list. C++ will not only let you iterate beyond either + end of an array, but it will let you change the values + beyond either end of the array with sometimes catastrophic + results.
+The phrase, be careful what you wish for
is a great one
+ to remember when programming in C++. Because C++ will
+ generally try to do everything you ask for.
+#include <iostream>
+using namespace std;
+
+// demonstrates what happens when iterating
+// outside of an array in C++,
+//also outputs the location of the value in memory
+int main(){
+ int myarray[] = {2,4,6,8};
+ for (int i=0; i<=8; i++){
+ cout << myarray[i] << endl;
+ cout << "id: " << &myarray[i] << endl;
+ }
+ 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"""
+def main():
+ mylist = [2,4,6,8]
+ print(mylist)
+ for i in range(5):
+ print(mylist[i])
+ print("id: "+str(id(mylist[i])))
+
+main()
+
+ The speed of C++ comes at the cost of minimal to no error checking. + Sometimes this can have perplexing results such as in the next example.
+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
+#include <iostream>
+using namespace std;
+
+// Demonstrates how in iterating outside
+// of an arry in C++, can change data in other places
+int main(){
+ int myarray[] = {2, 4};
+ int otherdata[]={777, 777};
+ for (int i=0; i<4; i++){
+ myarray[i]=0;
+ cout <<"myarray["<< i << "]=";
+ cout << myarray[i]<< endl;
+ cout << "add:" << &myarray[i] << endl;
+ }
+
+ for (int i=0; i<2; i++){
+ cout <<"otherdata["<< i << "]=";
+ cout << otherdata[i]<< endl;
+ cout << "add:" << &otherdata[i] << endl;
+ }
+
+ return 0;
+}
+
+
+"""Demonstrates how python protects from
+iterating past the end of a list
+and changing any other data"""
+def main():
+ mylist = [2, 4]
+ otherdata = [777, 777]
+ for i in range(4):
+ print(mylist[i])
+ print("id: "+str(id(mylist[i])))
+
+ for j in range(2):
+ print(otherdata[i])
+ print("id: "+str(id(otherdata[i])))
+
+main()
+
+ In the above example, what happened to otherdata[ ] in C++?
+ +Nothing. Everything is fine.
+Actually, there is a problem. Look carefully.
+All data was automatically reinitialized.
+No. C++ just does what you tell it to do.
+I have no idea. Please give me a hint.
+Try again. One of these is indeed correct. Look at the memory addresses.
+The first loop went out of bounds and wrote over the values in otherdata.
+Right!
+none of the above
+One of the above is indeed correct.
+What is the correct way to declare an array in C++?
+ +int myarray(5);
+Check the characters at the end of the array! Right now that is a function!
+myarray[5];
+You are forgetting something important!
+int myarray[5];
+Good work!
+None of the above.
+Check the characters at the end of the array!
+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 + C++ collection types.
+If you have used a Python dictionary, then you have used a hash table.
+ A maps
the key to the value.
+ Nevertheless, it is better to use the more precise term,
Each hash table has a
In Python, the dictionary data type represents the implementation of the hash table.
+ In C++, the
#include <unordered_map>+
The syntax for hash table access is much like we might expect
+ except that instead of using the index of the item for look-up, we
+ use the key. In both Python and C++, hash tables can be initialized with key-value pairs and
+ key-value pairs can also be added later as we see in the following example.
+ In C++, the keyword
+// 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>
+#include <unordered_map>
+#include <string>
+using namespace std;
+
+int main() {
+ unordered_map<string, string> spnumbers;
+
+ spnumbers = { {"one", "uno"}, {"two", "dos"} };
+
+ spnumbers["three"] = "tres";
+ spnumbers["four"] = "cuatro";
+
+ cout << "one is ";
+ cout << spnumbers["one"] << endl;
+
+ cout << spnumbers.size() << endl;
+}
+
+
+"""Python equivalent
+of the C++ code """
+def main():
+ spnumbers = {"one":"uno","two":"dos"}
+
+ spnumbers["four"]="cuatro"
+ spnumbers["three"]="tres"
+
+ print("one is", end=" ")
+ print(spnumbers["one"])
+
+ print(len(spnumbers))
+main()
+
+ It is important to note that hash tables are organized by the location given
+ by the hash function rather than being in any
+ particular order with respect to the keys. This makes look-up extremely fast.
+ Hence, although it is possible to iterate through a hash table in both C++ and Python,
+ it is an odd thing to do
+ because the data is not typically stored sequentially.
+ Iterators of an
+// 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>
+#include <unordered_map>
+#include <string>
+using namespace std;
+
+int main() {
+ unordered_map<string, string> spnumbers;
+
+ spnumbers = { {"one","uno"},{"two","dos"},{"three","tres"},{"four","cuatro"},{"five","cinco"} };
+
+ for (auto i=spnumbers.begin(); i!=spnumbers.end(); i++ ){
+ //auto is used to automatically detect the data type when
+ //a variable is declared. Use this ONLY when declaring complex
+ //variables.
+
+ cout << i->first << ":";
+ cout << i->second << endl;
+ }
+}
+
+
+"""Python equivalent
+of the C++ code """
+def main():
+ spnumbers = {"one":"uno","two":"dos","three":"tres","four":"cuatro","five":"cinco" }
+
+ for key in spnumbers:
+ print(key, end=":")
+ print(spnumbers[key])
+
+main()
+
+ Hash Tables have both methods and operators.
Match the Hash Table operations with their corresponding explination.
Feedback shows incorrect matches.
char cppchar = 'a'; // char values use single quotes
+string cppstring = "Hello World!"; // C++ strings use double quotes
+char cstring[] = {"Hello World!"}; // C-string or char array uses double quotes
+ In older versions of C++, you must use a
Because strings are sequences, all of the typical sequence operations work as you would expect.
+ In addition, the string library
+// This function concatenates the string hello World
+// Then it says where World begins in the concatenated string
+#include <iostream>
+#include <string>
+using namespace std;
+
+int main(){
+
+ string mystring1 = "Hello";
+ string mystring2 = "World!";
+ string mystring3;
+
+ mystring3 = mystring1 + " " + mystring2;
+ cout << mystring3 << endl;
+
+ cout << mystring2 << " begins at ";
+ cout << mystring3.find(mystring2) << endl;
+
+ return 0;
+}
+
+
+"""This does the same thing as the C++ function """
+def main():
+ mystring1 = "Hello"
+ mystring2 = "World!"
+
+ mystring3 = mystring1 + " " + mystring2
+ print(mystring3)
+
+ print(mystring2, end=" ")
+ print("begins at", end=" ")
+ print(str(mystring3.find(mystring2)))
+
+main()
+
+ Check your understanding by completing the following question.
+ + + +What is the correct definition of c-strings?
+ +An array of characters that ends with a terminating null character. i.e. \0
+Correct! a c-string is different from a string
+A sequential data structure consisting of zero or more characters
+Close, but that is the definition of a string, not a c-string
+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.
+Sorry, thats not a string or a c-string
+sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.
+No, that's a vector
+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
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_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.
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 unordered set
+#include <iostream>
+#include <unordered_set>
+using namespace std;
+
+void checker(unordered_set<char> set, char letter){
+ if(set.find(letter) == set.end()){
+ cout << "letter " << letter << " is not in the set." << endl;
+ }
+ else{
+ cout << "letter " << letter << " is in the set." << endl;
+ }
+}
+
+int main(){
+unordered_set<char> charSet = {'d', 'c', 'b', 'a'};
+
+char letter = 'e';
+checker(charSet, letter);
+charSet.insert('e');
+checker(charSet, letter);
+return 0;
+}
+
+ the
Match the Unordered Sets operations with their corresponding explination.
Feedback shows incorrect matches.
Vectors are a class that is available through a library called the Standard Template Library (STL), and one uses a
#include <vector>+ +
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
+#include <iostream>
+using namespace std;
+
+int main() {
+ int nums[] = {1,3,6,2,5};
+ //Divide the size of the array (in bytes) by the size of a single element (in bytes)
+ // to get the total number of elements in the array.
+ int numsSize = sizeof(nums)/sizeof(nums[0]); // Get size of the nums array
+
+ for (int index=0; index<numsSize; index++) {
+ cout << nums[index] << endl;
+ }
+
+
+ // Simpler Implementation that may only work in
+ // Newer versions of C++
+
+ // for (int item:nums) {
+ // cout << item << endl;
+ // }
+
+ return 0;
+}
+
+ An optional secondary version of the
Then, the value at that index in the array is printed to the console.
+ +
+// function that uses a vector to square
+// every number from 0 to 49
+// uses the reserve operation to save space in memory
+#include <iostream>
+#include <vector>
+using namespace std;
+
+int main(){
+
+ vector<int> intvector;
+ intvector.reserve(50);
+
+ for (int i=0; i<50; i++){
+ intvector.push_back(i*i);
+ cout << intvector[i] << endl;
+ }
+ return 0;
+}
+
+
+"""Uses a list to square every
+number from 0 to 49 """
+def main():
+ intlist=[]
+ for i in range(50):
+ intlist.append(i*i)
+ print(intlist[i])
+
+main()
+
+ In the above example, the use of
+// function that uses a vector to square
+// every number from 0 to 49
+// and does not use reserve.
+// shows amount of space used
+#include <iostream>
+#include <vector>
+using namespace std;
+
+int main(){
+
+ vector<int> intvector;
+ // without intvector.reserve(50);
+
+ for (int i=0; i<50; i++){
+ intvector.push_back(i*i);
+ cout << intvector[i] << endl;
+ cout << "capacity: " << intvector.capacity() << endl;
+ }
+ 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
+
+#include <iostream>
+#include <vector>
+using namespace std;
+
+int main(){
+
+ vector<int> intvector;
+ intvector.reserve(10);
+
+ for (int i=0; i<10; i++){
+ intvector.push_back(i);
+ }
+
+ for (int i=0; i<=10; i++){
+ cout << "intvector[" << i << "]="
+ <<intvector[i] << endl;
+ }
+
+ return 0;
+}
+
+
+"""Demonstrates python's protections
+against iterating outside of a list"""
+def main():
+ intlist=[]
+ for i in range(10):
+ intlist.append(i)
+
+ for i in range(11):
+ print("intlist[" + str(i) + "]=" + str(intlist[i]))
+
+main()
+
+ Match the Vector operations with their corresponding explination.
Feedback shows incorrect matches.
Match the Vector operations with their corresponding explination.
Feedback shows incorrect matches.
Which of the following is the biggest difference between a C++ array and a C++ vector?
+ +Vectors can change size.
+Right! Good job!
+Vectors offer all of the features and protections of Python lists
+Not all of the protections of lists are offered by vectors; one can still iterate off of either end.
+Vectors don't use contiguous memory, so elements can be inserted.
+No. Although elements can be inserted in vectors, they do require contiguous memory.
+more than one of the above
+No. Only one of the above is correct.
+none of the above
+One of the above is indeed correct.
+What good is the
Nothing. It is completely optional.
+It is optional but it does serve a purpose. Try again.
+Using it will save time if you know the maximum size needed.
+Right!
+It is required so memory can be allocated.
+It is not required.
+none of the above
+One of the above is indeed correct.
+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.
+ +a grouping of a number of data items (possibly only zero or one) that have some shared significance or need to be operated upon together.
+ +a collection consisting of key-value pairs with an associated hash function that maps the key to the associated value.
+ +unable to be modified.
+ +the ability of an object to be modified.
+ +An unordered data structure consisting of unique, immutable data values.
+ +A sequential data structure consisting of zero or more characters.
+ +sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.
+ +unit of data used by a particular processor design.
+ ++ A statically allocated C++ array is an ordered collection of one or more C++ data values of identical type stored in contiguous memory. +
++ A vector is a dynamically allocated array with many useful methods. It is more similar to the Python list than the array. +
++ C++ strings are a sequential collection of zero or more characters. They are very similar to Python strings. +
++ A hash table is used to store keys-value pairs. It applies a related hash function to the key in order to compute the location of the associated value. Look-up is typically very fast. +
++ A set is an unordered collection of unique values. +
+Which C++ structure is the best choice for a group of ordered data of a fixed length?
+ +array
+Correct!
+hash table
+No. hash tables are not ordered. +
+string
+A string would only work for character data. Try again. +
+vector
+There is a better choice given that the group is fixed length. +
+more than one of the above
+Only of the above is best. +
+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 Python, we write a simple if statement in the following way:
+if condition: + statement1 + statement2 + ...+
In C++ this same pattern is simply written as:
+if (condition) {
+ statement1
+ statement2
+ ...
+}
+ Once again you can see that in C++ the curly braces define a block
+ rather than indentation. In C++ the parenthesis around the condition
+ are required because
The if-else statement in Python looks like this:
+if condition: + statement1 + statement2 + ... +else: + statement1 + statement2 + ...+
In C++ this is written as:
+if (condition) {
+ statement1
+ statement2
+ ...
+}
+else {
+ statement1
+ statement2
+ ...
+}
+ C++ does not have an elif pattern like Python. In C++ you can get the + functionality of an elif statement by nesting if and else. Here is a + simple example in both Python and C++.
+ +
+# demonstrates if,elif, and else statements in python
+def main():
+ grade = 85
+
+ if (grade < 60):
+ print('F')
+ elif (grade < 70):
+ print('D')
+ elif grade < 80:
+ print('C')
+ elif grade < 90:
+ print('B')
+ else:
+ 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;
+
+ int main() {
+
+ int grade = 85;
+
+ if (grade < 60) {
+ cout<<'F'<< endl;
+ }
+ else { /* if, elif, and else statement can be used
+ inside of themselves to allow for sub options */
+ if (grade < 70) {
+ cout<<'D'<< endl;
+ }
+ else {
+ if (grade < 80) {
+ cout<<'C'<< endl;
+ }
+ else {
+ if (grade < 90) {
+ cout<<'B'<< endl;
+ }
+ else {
+ cout<<'A'<< endl;
+ }
+ }
+ }
+ }
+ return 0;
+ }
+
+ We can get closer to the look of the elif
+ //Shows how to put conditional statements together,
+ //specfically putting "else if" after an "if" statement.
+ #include <iostream>
+ using namespace std;
+
+ int main() {
+
+ int grade = 85;
+
+ if (grade < 60) {
+ cout<<'F'<<endl;
+ }
+ else if (grade < 70) {
+ cout<<'D'<<endl;
+ }
+ else if (grade < 80) {
+ cout<<'C'<<endl;
+ }
+ else if (grade < 90) {
+ cout<<'B'<<endl;
+ }
+ else cout<<'A'<<endl;
+
+ return 0;
+ }
+
+ C++ also supports a
To write the grade + program using a switch statement we would use the following:
+ +
+ // Shows how to use a Switch statement.
+
+ #include <iostream>
+ using namespace std;
+
+ int main() {
+
+ int grade = 85;
+
+ int tempgrade = grade/10;
+ switch(tempgrade) { /*switch cases allow for different options based on
+ the value of temp grade similar to if statements*/
+ case 10:
+ case 9:
+ cout << "The grade is A" << endl;
+ break;
+ case 8:
+ cout << "The grade is B" << endl;
+ break;
+ case 7:
+ cout << "The grade is C" << endl;
+ break;
+ case 6:
+ cout << "The grade is D" << endl;
+ break;
+ default:
+ cout << "The grade is F" << endl;
+ }
+
+ return 0;
+ }
+
+ Frankly, the
T/F: It is necessary to have an else statement after an if statement. (Hint: Test it out in the code above.)
+ +True
+Not quite, try modifying the code above to test it out.
+False
+Good job!
+When indicating the condition for a C++ if statement, what symbols are used?
+ +{ }
+No. Try again.
+[ ]
+No. Try again.
+( )
+Right!
+Any set of matching braces may be used.
+No. Try again.
+none of the above
+One of the above is indeed correct.
+When using a switch, what prevents all the cases from passing as correct?
+ +Ending statements with ;
+No. This is always needed.
+Using a break statement
+Good job!
+Enclosing each cases with { }
+No. Try again.
+Setting a default case
+No. This is a good idea, but it will not help.
+What symbol is used to indicate the and
in C++ such as in a compound condition?
||
+No, this means "or".
+and
+No, this is Python.
+!
+No, this means "not"
+&&
+Very good!
+Even though the
+#include <iostream>
+using namespace std;
+
+int main() {
+ for (int i = 0; i < 10; i++){
+ cout << i << "hello world" << endl;
+ }
+ }
+
+ In the example above, the
A common use of the
+#include <iostream>
+using namespace std;
+
+ // squares the numebers in range 5
+ // ex. 0*0, 1*1, 2*2 ...
+ int main() {
+ for (int i=0; i<5; i++) {
+ cout << i*i << " ";
+ }
+
+ return 0;
+ }
+
+ The code will use
#include <iostream>
+using namespace std;
+
+int main() {
+
+ for (int counter=0; counter<4; counter++) {
+ cout << counter * 2 << " ";
+ }
+
+ return 0;
+}
+Using the code above please select the answer that should appear?
+ +0 2 4 6
+Good Job!
+0 0 0 0
+Not quite, take another look at the operation happening in the cout line
+Runtime error
+Not quite, take another look at the for loop
+0 1 2 3
+Not quite, take another look at the operation happening in the cout line
+all of the above
+Terminates the current block of code and resumes the program outside of it.
+ +A condition in a switch statement for a variable to be tested against.
+ +A statement that tests whether a condition is true or false
+ +A series of instructions repeated infinitely or until a condition is met.
+ +A statement that tests a variable against possible conditions for it.
+ +Like Python C++ also supports the
Unlike Python, C++ does not support the use of the
C++ also supports a
C++ supports the use of Boolean expressions in
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
As we noted earlier, algorithms require two important control + structures: iteration and selection. Both of these are supported by + 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
int counter = 1;
+while (counter <= 5) { /*Use of an interactive method until the
+ the loop ends */
+ cout << "Hello, world" << endl;
+ counter = counter + 1;
+}
+
+Console output:
+Hello, world
+Hello, world
+Hello, world
+Hello, world
+Hello, world
+ prints out the phrase Hello, world
five times. The condition on the
+
The
while ((counter <= 10) && (!done)) {
+...
+ would cause the body of the statement to be executed only in the case
+ where both parts of the condition are satisfied due to the and operator (
Here are some of the logical operators that are useful for true-false boolean statements in C++.
+and - && + +or - || + +not equal to - != + +not - ! + +greater than - > + +less than - < + +greater than +or equal to - >= + +less than +or equal to - <=+
These are the same as we saw in earlier chapters.
+#include <iostream>
+using namespace std;
+
+int main(){
+ int counter = 0;
+ while (counter <= 1) {
+ cout << "Hello, world!" << endl;
+ }
+};
+Using the code above please select the answer that should appear.
+ +"0" is written 1 time.
+Take a look at the cout line.
+"Hello world!" is written 1 time.
+Take a closer look at the while loop
+"Hello world!" is written infinitely many times.
+Right! because counter is never greater than one, thus making the while loop infinite.
+None of the above.
+Not quite, take another look.
+There are two types of errors that typically occur when writing
+ programs. The first, known as a
int main() {
+ int i = 10
+ return 0;
+}
+
+>> exit status 1
+ main.cpp: In function 'int main()':
+ main.cpp:3:5: error: expected ',' or ';' before 'return'
+ return 0;
+ ^~~~~~
+ In this case, the C++ compiler has found that it cannot complete + 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
Most of the time, beginning programmers simply think of exceptions as + fatal runtime errors that cause the end of execution. However, most + 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 catch
main.cpp: In function 'int main()': +main.cpp:5:13: warning: division by zero [-Wdiv-by-zero] + cout << 10/0; + ~~^~ +exit status -1+
We can handle this exception by creating a divide function that can
+ catch
the exception
+ and prints a message back to the user in the event that an exception
+ occurs. For example, try changing the values assigned to firstNum and secondNum
+ in the code below:
+ +++ ++// Shows exception handling using try,throw, +// and catch in order to output +// an error message to the console +#include <iostream> +using namespace std; + +double div(double num1, double num2) { + if (num2 == 0) { + // If the second number is 0, throw this error + throw "Cannot divide by 0!\n"; + } + + return num1 / num2; +} + +int main() { + // Get input from the user + float firstNum=10; + float secondNum=0; + + try { + // Attempt to divide the two numbers + double result = div(firstNum, secondNum); + cout << "result of division: " << result << endl; + + } + catch (const char *err) { + // If an error is thrown, print it + cout << err; + } + + return 0; +} ++
This will catch the fact that an exception is raised by
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 file.txt
. The program will prompt
+ the user for a filename and can catch if that file does not exist or the default
+ file.txt
does not exist. This is another useful application for Error handling.
#include <fstream>
+#include <iostream>
+using namespace std;
+
+void printFile(char filename[32]) {
+ ifstream in_stream;
+ in_stream.open(filename);
+
+ if (!in_stream.good()) {
+ // Throws an error
+ in_stream.close();
+
+ throw "\nA file by that name does not exist!";
+ }
+
+ char ch;
+
+ cout<<endl;
+ while (!in_stream.eof()) {
+ cout << ch;
+ ch = in_stream.get();
+ }
+ cout << endl;
+
+ in_stream.close();
+}
+
+int main() {
+ char filename[32];
+ cout << "Filename: ";
+ cin >> filename;
+
+ try {
+ // Tries to print the file
+ printFile(filename);
+ }
+ catch (const char *msg) {
+ // Runs if error is thrown
+ cerr << msg << endl; //cerr is used to output errors similar to cout.
+
+ // Uses default file to print instead
+ try {
+ char defaultFile[32] = "file.txt";
+ printFile(defaultFile);
+ }
+ catch (const char *msg) {
+ cerr << "Default file not found!" << endl; //cerr is used to output errors similar to cout.
+ }
+ }
+
+ return 0;
+}
+ 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
+A syntax error is an error that occurs due to typing error or wrong statement that is not allowed in a language. This can be easily caught as the program does not run until this is fixed.
+Logic errors are errors that happen not due to error in how the code is written, but because the code is producing an unintended or unexpected value such as a division by 0 leading to an undefined value.
+logic errors can be caught by using
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.
a response to an unusual circumstance while a program is running
+ +an error in which the program/code functions, but performs incorrectly
+ +an error that occurs when a program runs
+ +an error in the structure of a statement or expression of code
+ +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
The following example function returns the average hours worked over the array of + integers (note that we need to also pass in the number of elements in that array + because the array parameter list[] does not include that information):
+double average( int list[], int length ) {
+ // It is correct syntax to omit the array length on the array itself.
+ double total = 0;
+ //return type double which indicates that a decimal is being returned
+ int count;
+ for( count = 0; count < length; count++ ) {
+ total += double(list[count]);
+ };
+ return (total / length);
+}
+ 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:
+void add_lists( int first[], int second[], int total[], int length ) {
+ //return type void which indicates that nothing is returned
+ int count;
+ 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
void add_lists( const int first[], const int second[], int total[], int length ) {
+ //return type void which indicates that nothing is returned
+ int count;
+ for( count = 0; count < length; count++ ) {
+ total[count] = first[count] + second[count];
+};}
+ These changes would ensure that the compiler will then not accept any statements within the function's definition that potentially modify the elements of the arrays first or second.
+In general, we can hide the details of any computation by defining + a function. A function definition requires a name, a group of + parameters, a return type, and a body. It may either return a variable, value, or nothing (specified by the keyword void). For + example, the simple function defined below returns an integer which is the double of the + value you pass into it.
+ ++ +++ ++#include <iostream> +using namespace std; + +// function that multiplies a number by 2 + int timesTwo(int num) { + /* return type int which indicates + that an integer is being returned */ + return num*2; +} + +int main() { + /* return type int which indicates that + an integer is being returned */ + cout<<timesTwo(5)<<endl; + + return 0; +} ++
The syntax for this function definition includes the name, inside the box,
+ simply compute the result of
Let us look at a similar function.
+ ++ +++ ++#include <iostream> +using namespace std; + +// function that multiplies a number by 2 +// except it does not anything it only outputs to the console +void timesTwoVoid(int num) { + /* return type void which indicates + that an nothing is being returned */ + cout<< num*2<<endl; +} + +int main() { + /* return type int which indicates that + an integer is being returned */ + timesTwoVoid(5); + + return 0; +} ++
The
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
+ correct value. The equation
+
+// returns the square root of a number as a double
+#include <iostream>
+using namespace std;
+
+double squareroot(double n) { /*return type double which indicates
+ that a decimal is being returned*/
+ double root = n / 2;
+
+ for (int i = 0; i < 20; i++) {
+ root = (.5) * (root + (n / root));
+ }
+
+ return root;
+}
+
+int main() {
+ cout << squareroot(9) << endl;
+ cout << squareroot(4563) << endl;
+
+ return 0;
+}
+
+
+// function that returns the output number of steps walked
+#include <iostream>
+using namespace std;
+
+void dogWalk(int steps){
+ for (int step = 0; step < steps; step++){
+ cout << "dog walked "<< step << " steps!"<< endl;
+ }
+}
+
+int main() {
+ dogWalk(11);
+
+ return 0;
+}
+
+ What is the correct return type of the function above
void
+Correct, nothing is returned!
+int
+Not quite, check the value preceding the name of the function!
+dog
+Not quite, dog is not even a data type!
+dogWalk
+Not quite, that is the name of the function itself!
+In C++ programming, two or more functions can have same + name when they can be distinguished by the parameters. + Hence, C++ allows function overloading when either the data types of the parameters differ + or the number of parameters differ.
+Overloading is a nice feature of the C++ language. + Python does not offer function overloading, so accomplishing the same task in + Python requires a different technique.
+See the following example where an optional parameter is used to accomplish the + same task.
+
+// demonstrates how function overloading works
+// by changing the parameters on the inputs.
+#include <iostream>
+using namespace std;
+
+void myfunct(int n) {
+ cout << "1 parameter: " << n <<endl;
+}
+
+void myfunct(int n, int m) {
+ cout << "2 parameters: " << n;
+ cout << " and " << m <<endl;
+}
+
+int main() {
+
+ myfunct(4);
+ myfunct(5, 6);
+ myfunct(100);
+
+ return 0;
+}
+
+
+"""Demonstrates the use of multiple parameters using a single function"""
+def myfunct(n, m=None):
+ if m is None:
+ print("1 parameter: " + str(n))
+ else:
+ print("2 parameters: " + str(n), end="")
+ print(" and ", str(m))
+
+def main():
+ myfunct(4);
+ myfunct(5, 6);
+ myfunct(100);
+
+main()
+
+ What are benefits of function overloading?
+ +Helps keep consistency in the way your functions are named across your program.
+Take a look at the other answers as well...
+Functions that do similar tasks differ based on parameters rather than by name.
+Take a look at the other answers as well...
+A function in essence can fulfill multiple tasks depending on the parameters.
+Take a look at the other answers as well...
+Removes the limit on how many parameters can be written or passed.
+Wrong! Function overloading has nothing to do with removing the limit of parameters.
+Here's a self check that really covers everything so far. You may have
+ heard of the infinite monkey theorem? The theorem states that a monkey
+ hitting keys at random on a typewriter keyboard for an infinite amount of
+ time will almost surely type a given text, such as the complete works of
+ William Shakespeare. Well, suppose we replace a monkey with a C++ function.
+ How long do you think it would take for a C++ function to generate just one
+ sentence of Shakespeare? The sentence we'll shoot for is: methinks it is
+ like a weasel
You're not going to want to run this one in the browser, so fire up your favorite + C++ IDE. The way we'll simulate this is to write a function that generates a string + that is 28 characters long by choosing random letters from the 26 letters in the + alphabet plus the space. We'll write another function that will score each + generated string by comparing the randomly generated string to the goal. + Hint: You will need to import the <random> library for this.
+A third function will repeatedly call generate and score, then if 100% of + the letters are correct we are done. If the letters are not correct then + we will generate a whole new string. To make it easier to follow your program's + progress this third function should print out the best string generated so far + and its score every 1000 tries.
+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 + 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
Consider the following two function definitions:
+void functionExample( int inputVar ) { /*return type void which indicates that
+ nothing is being returned*/
+ int nextVar = inputVar * 2;
+ inputVar = 4;
+
+ cout << "nextVar = " << nextVar << " inputVar = " << inputVar;
+}
+
+void callingFunction() { /*return type void which indicates
+ that nothing is being returned*/
+ int myVar = 10;
+
+ functionExample( myVar );
+ cout << "myVar = " << myVar;
+}
+ When the function
nextVar = 20 inputVar = 4+
Notice what happens when
myVar = 10+
In other words, any changes to the variables are local to the function, which is exactly what we want.
+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 &
to the end of the type name in the formal parameter list in the function
+ declaration and header. When you do this, any changes to the values of the parameters will
+ change the value of the arguments as well.
An example of a function where this is useful is a function that takes two values
+ as input and swaps their order. Consider the following program fragment of a function
+ called
+ +++ ++#include <iostream> +using namespace std; + +// swap_values() function definition +// Interchanges the values located by variable1 and variable2. + +// Notice that this function does not return anything! +void swap_values(int &variable1, int &variable2) { + int temp; // temporary storage for swap + + temp = variable1; + variable1 = variable2; + variable2 = temp; +} + +int main( ) { + int first_num, second_num; + first_num = 7; + second_num = 8; + + cout << "Two numbers before swap function: 1) " << first_num << " 2) " << second_num << endl; + swap_values(first_num, second_num); + cout << "The numbers after swap function: 1) " << first_num << " 2) " << second_num; + + return 0; +} ++
For this program &
‘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>
+using namespace std;
+
+void func1(int var1, int var2){
+ int temp;
+ temp = var1;
+ var1 = var2;
+ var2 = temp;
+}
+
+void func2(int &var1, int &var2){
+ int temp;
+ temp = var1;
+ var1 = var2;
+ var2 = temp;
+}
+
+int main(){
+ int num1 = 2;
+ int num2 = 3;
+
+ func1(num1, num2);
+ cout << "results of func1:" << endl;
+ cout << "num1: " << num1 << ", num2: " << num2 << endl;
+ func2(num1, num2);
+ cout << "results of func2:" << endl;
+ cout << "num1: " << num1 << ", num2: " << num2 << endl;
+
+ return 0;
+}
+
+
What is the difference between
func2 is a pass-by-reference function, meaning that the values passed into the function are the direct memory references of the original variables.
+Correct!
+func1 is a pass-by-reference function, meaning that the values passed into the function are the direct memory references of the original variables.
+No, func1 is simply using copies of the original variables as input because it is not using "&."
+func1 is a pass-by-value value function, meaning that the values passed into the function are copies of the original variables.
+Correct!
+func2 is a pass-by-value value function, meaning that the values passed into the function are copies of the original variables.
+No, func2 is using the direct memory references of the original variables because its input parameters are using "&."
+Why does adding the &
to parameters in the
The "&" forces variables to change in the global scope, resulting in the two variables not exclusively changing inside of the function.
+No, "&" has nothing to do with altering integers in the global scope.
+The "&" passes the location where the two variables are stored, resulting in the two variables switching memory references.
+Correct!
+The "&" in this function is incorrectly used, resulting in an overlapping memory reference.
+No, the use of "&" here is correct. Read over the active code 4 example earlier in the section.
+None of the above
+No, one of the above is definitely true.
+the data passed to parameter.
+ +keyword that makes a variable or value constant and unchanging.
+ +a section of code that performs a procedure and is usually named.
+ +specifying more than one definition for the same function name within the same scope.
+ +a variable in a function or method definition that accepts data passed from an argument.
+ +a value that indicates a place in a computer's memory.
+ +Keyword indicating a function has no return value.
+ +Like Python, C++ supports the use of functions.
+In C++, a function definition requires a name, a group of parameters, a return type, and a body.
+Non-fruitful functions in C++ must contain the keyword
You can pass variables by value as well as by reference in C++ functions. Passing by reference utilizes the use of pointers.
+Pass by reference is useful when you require a function to return multiple variables.
+To pass an array to a function you need to use an array parameter. The array parameter is denoted by the array variable name followed by set of square brackets ([ and ]).
+Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
Drag each glossary term to its' corresponding definition.
Feedback shows incorrect matches.
File operations, such as opening and closing files, are often a source of runtime
+ errors for various reasons. Well-written programs always should include error checking
+ and Handling routines for possible problems dealing with files. Error checking
+ and handling generally involves the programmer inserting statements in functions
+ that perform I/O to check if any of the operations have failed. In C (the predecessor to C++),
+ 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
in_stream.fail();+
This function returns
The following example code fragment safely quits the program entirely in case an I/O operation fails:
++++ ++ #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 1
versus a 0
, indicating an Error has occurred.
For more on Error Handling, see section 1.11.
+File handling in C++ also uses a
You must declare any file streams before you use them to read and write data. For example, the following statements inform the compiler to create a stream called
ifstream in_stream; +ofstream out_stream;+
In modern versions of C++, you can use the <string> library for filenames,
+ but earlier versions of C++ required the use of C-strings.
+ The program above will try to open the file called rawdata.txt
and
+ output its results to a file called neat.dat
every time it runs,
+ which is not very flexible. Ideally, the user should be able to enter
+ filenames that the program will use instead of the same names.
+ We have previously talked about the myFileName.dat
+ can be stored in an array of chars called a
// Syntax: char C-string_name[LEN]; +// Example: +char filename[16];+
This declaration creates a variable called
+++
+ + +Warnings: + ++
+ +- +
+The number of characters for a c-string must be one greater than the number of actual characters!
+- +
+Also, LEN must be an integer number or a declared const int, it cannot be a variable.
+
strings
, which can be confusing.
Typically,
Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function myFile.txt
, assuming a file named that exists in the current directory, and connect
in_stream.open("myFile.txt");
+ Once connected, the program can read from that file. Pictorially, this is what happens:
+ +the
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 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
in_stream.close();+
To close the file for
out_stream.close();+
Answer the question below concerning the use of the
Say you wanted to add some text to a file that already has important information on it.
+ Would it be a good idea to first use
Yes, ofstream is required to edit the file.
+Wrong! Even though it is required for editing files, using ofstream first will cause problems when it opens a file that has previous work saved on it.
+Yes, using ifstream will wipe the file clean without using ofstream first.
+Wrong! ifstream is only used to read files, therefore it will never edit the contents of one.
+No, using ofstream on a file that already has information on it will clear the entire file.
+Correct!
+No, ofstream is exclusively used for reading files.
+Wrong! ifstream is used to read files instead.
+A function that is associated with a certain type of object is called a
// 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); + +// Use cout's setf function again, but this time +// The argument tells cout to show the decimal point +cout.setf(ios::showpoint); + +// Use cout's member function, called Precision +// The argument indicated to display 2 digits of precision +cout.precision(2);+
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 + + 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; + + // 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 + } + + // 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; + + // 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; + + // 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(); + + cout << "End of Program." << endl; + + return 0; ++
As file I/O streams work in a similar way to >>
and <<
perform the same direction of data for files, with the exact same syntax.
For example, execution of the following statement will write the number 25, a line break, the number 15, and another line break into the out_stream output stream.
+out_stream << 25 << endl; +out_stream << 15 << endl;+
The line break after the value 25 is important because data in a text file is typically seperated by a space, tab, or a line break. Without the line break, the value 2515 will be placed in the file, and subsequent read operations on that file would consider 2515 as a single value. For example, suppose that after the previous statement, the program opens the same file with the input stream in_stream. The following statement would put the number 25 into the variable
int inputn; +in_stream >> inputn;+
In the above program, you see that the input and output streams are passed to the file
+ via flow
, they are changed.
+ For this reason, all streams will always be passed by reference.
File handling in C++ uses
End-of-File or
Which of the following are libraries for C++ input and output? (Choose all that are true.)
+ +fstream
+Yes, fstream is library for handling file input and output.
+ifstream
+No, ifstream is an object type for handling input.
+ofstream
+No, ofstream is an object type for handling output.
+iostream
+Yes, iostream is a library for handling console input and output.
+Drag the corresponding library to what you would use it for.
+Which library is used for which task?
Fill in the blank with the value of
#include <fstream>
+ #include <cstdlib>
+ #include <iostream>
+ using namespace std;
+
+ main(){
+ ifstream in_stream;
+ ofstream out_stream;
+ int inputn;
+
+ out_stream.open("anotherFile.txt");
+ out_stream << 25;
+ out_stream << 15 << endl;
+ out_stream << 101 << endl;
+
+ in_stream.open("anotherFile.txt");
+ in_stream >> inputn;
+ cout << inputn;
+ in_stream >> inputn;
+ }
+ That is the correct answer! Good job!
No. Hint:
No. Hint:
No. Hint: note that there is no space between the first 25 and 15!
Match the words to thier corresponding definition.
Feedback shows incorrect matches.
So far, the assumption was that the programmer knew exactly how much data to read from + an open file. However, it is common for a program to keep reading from a file without + any idea how much data exists. Most versions of C++ incorporate an end-of-file (EOF) + flag at the end of the file to let programs know when to stop. + 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()
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
The following two code fragments highlight the possibilities:
+Using the
while(!in_stream.eof()) {
+ // statements to execute
+ // while EOF has not been
+ // reached
+}
+ Using the >> operator
+while(in_stream>>inputn) {
+ // statements to execute
+ // while reads are successful
+}
+ 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
+++ ++ // 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); + + 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); + } + + 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 ++
This is the
10 -20 30 -40 +500 300 -100 1000 +-20 2 1 2 +10 -20 30 -40+
And this is the expected output
++10.00000 + -20.00000 + +30.00000 + -40.00000 + +500.00000 + +300.00000 + -100.00000 ++1000.00000 + -20.00000 + +2.00000 + +1.00000 + +2.00000 + +10.00000 + -20.00000 + +30.00000 + -40.00000+ +
The input file neat.dat
to output the results.
What are good use cases for EOFs in C++ programming?
+ +To keep a program from writing into other files.
+Yes, EOFs are intended to prevent the program from overwriting a file.
+To keep a program from stopping.
+Not quite, the point of EOFs is to do the opposite.
+To make sure you do not overflow into temporary buffer.
+Yes, EOFs prevent overflow into temporary buffer.
+To stop an input files stream.
+Yes, EOFs stop input file streams.
+An array of characters that ends with a terminating null character. i.e.
A function that's associated with a certain type of object; this function is called a member function of that object.
+ +An abstraction that allows you to send or receive an unknown number of bytes in input or output. It is a metaphor for a stream of water.
+ +A flag at the end of the file to let programs know when to stop.
+ +A time honored tradition in computer science is to write a program
+ called hello world.
The hello world
program is simple and easy.
+ No logic errors are possible to make, so getting it to run relies only on
+ understanding the syntax. Let's look at an easy version of hello world
+ in Python:
+print("Hello World!")
+
+ Now, lets look at a more complicated
version of the hello world
program with a
+
+def main():
+ print("Hello World!")
+main()
+
+ Next, lets look at the same program written in C++:
+ +
+#include <iostream>
+
+int main(){
+
+ std::cout << "Hello World!\n";
+ return 0;
+}
+
+ The above program can alternatively be written as follows to allow + better facilitate standard input and output:
+ +
+#include <iostream>
+using namespace std;
+
+int main(){
+ cout << "Hello World!\n";
+ return 0;
+}
+
+ What we see is that at the core there are a few similarities with the
+ complicated Python version, such as the Hello world
. However, in C++ there is a lot more
+ stuff around the edges that make it harder to see the core of the program.
+ Do not worry! An important skill for a computer scientist is to learn what
+ to ignore and what to look at carefully. You will soon find that there
+ are some elements of C++ that will fade into the background as you
+ become used to seeing them. One thing that will help you is to learn a
+ little bit more about C++.
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
First, we must type the hello world program into a file and save that file
+ using a name like
Now you may be wondering what good is this extra step? What does + compiling do for us? There are a couple of important benefits we get + from compiling:
+Early detection of errors
+Faster program execution
+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
When the compiler does the translation it can find many different kinds + of errors. For example if you make a typo or forget to declare a variable + the compiler will find these and point them out to you before you ever + run the program. We will look at some examples of errors that the compiler + catches shortly. Chances are you may create some on your own very soon too, + but first let's talk about each of the statements in a C++ program.
+ +
+
You can think of the
In Python, an import statement looks like:
+import classname+
There are two ways to use
#include <libraryname> +#include "filename"+
Here the angle-brackets
Unlike Python, every C++ program
The
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.
+ +
+#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. + You will likely learn to appreciate this when you are debugging.
+Without peeking, see if you can put the following code in the correct order.
+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
+
The triple quoted docstring in Python is often used for automatically
+ processing documentation.
+ There is no equivalent in the C++ standard to the triple-quoted docstring in Python.
+ However, the symbol groups
+
// The remainder of this line is a C++ comment which is ignored by the compiler + +/* This is a multi-line C++ comment that can +span many lines, beginning and ending with the given symbols */+
We often have a need to interact with users, either to get data or to provide some sort of result.
+ The C++
A sink
.)
+ Output streams send data out, and the standard output stream character output
.
+ Much like the Python 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>
+using namespace std;
+
+int main(){
+ cout << "Ever heard of rubber duck debugging?" << endl;
+ cout << " __ " << endl;
+ cout << " <(o )___-" << endl;
+ cout << " ( .__> /" << endl;
+ cout << " `----' " << endl;
+}
+
+ In addition to being able to output to the standard output, we want to be able to take input from the user.
+ The command character input
and it makes getting input from the standard input device (usually the keyboard) relatively easy.
+ The input operator
Here is an example that uses
The active code below is an example of what getting input from the + user might look like. Feel free to change 12.4 to other values!
+ +
+#include <iostream>
+using namespace std;
+
+int main() {
+
+ //declares num as a floating point number variable
+ float num = 12.4; // Note: cin is not currently working in activecode
+
+ // Displays this text to the console
+ cout << "Give me a number:" << endl;
+
+ // Takes the user's input and stores it in num
+ cin >> num;
+
+ // Displays to the console
+ cout << "This is your number doubled: " << num*2 << endl;
+
+ return 0;
+}
+
+ In this example, you may note the line
We will talk more about type declarations in the section on data types, and + we will go into more depth on input and output later when we discuss + C++ streams and file handling.
+Match Compiler and Interpreter to the correct definition.
Correctly rearrange the code below to implement hello world in C++:
+console input
. It is the standard input statement in C++.
A comment is a programmer-readable explanation in the source code of a computer program (
A compiler generally transforms code written in a high-level programming language like C++ into a low-level programming language like machine code in order to create an executable program.
+ +console output
. It is the standard output statement in C++.
A dynamically typed programming languages is one in which variables need not necessarily be defined before they are used, and can change during execution.
+ +Header files are library files that contain a variety of useful definitions. They are imported into any C++ program by using the pre-processor #include statement.
+ +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.
+ +An interpreter directly executes statements in a scripting language without requiring them to have been compiled into machine language.
+ +machine code is a computer program written in instructions that can be directly executed by a computer's CPU.
+ +A statically typed programming languages is one in which variables must be defined before they are used and cannot change during execution.
+ +This book assumes that you are already familiar with the
+
Next, we will look at the primary constructs that are common + to nearly all programming languages:
++++
+- +
+Using code libraries
+- +
+Documenting with comments
+- +
+The main function
+- +
+Writing output to the screen
+- +
+Reading input from the keyboard
+- +
+Data types and operators
+- +
+Conditionals
+- +
+Loops
+
Once we have the basics of C++ behind us we will move on to look at the + additional useful features of C++ including:
++++
+- +
+Functions and their parameters
+- +
+File operations
+- +
+Exception handling
+
Please note that this book is a work in progress. + Updates and new versions are likely to be forthcoming.
++ 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.
+*/
+#include <iostream>
+using namespace std;
+
+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.
+Every C++ program must have a function which begins as
C++ statements are ended by a semi-colon.
+White space is mostly meaningless in C++, but all C++ code blocks must be surrounded by curly brackets {}, rather than using indentation to delineate blocks as is done in Python.
+What symbol or set of symbols will begin a comment in C++ when the comment extends only to the end of the line?
+ +<!-
+No, <!- is used in html to begin comments, but it is not used in C++.
+⋕
+No, ⋕ is used in Python for comments, but in C++ it is used for compiler directives such as loading a code library. +
+//
+Correct! +
+@
+No, @ is not used in C++. +
+none of the above
+One of the above is correct. +
+True or False: In both Python and C++, multi-line comments begin with ``/*`` and end with ``*/``.
+ +True
+Sorry, multi-line comments are possible in both languages, but they look different.
+False
+Right! In C++ multiline comments begin with /* and end with */. In Python, one could use a triple quoted string. +
+Given a variable called x. What statement will print the contents of x?
+ +cout x;
+Partially right. The object `cout` stands for character output and you need it, but you will also need to use the insertion operator <<.
+output x;
+No, output is not a C++ command or object. +
+print x;
+No, print is a Python command, but is not used in C++. +
+none of the above
+The correct statement would be "cout << x;" or "std:cout << x;" but the insertion operator is certainly needed. +
+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.
That's Python, not C++!
That's Python, not C++!
That's C, not C++!
Incorrect. Please try again.
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.
This short ebook is intended to help Python programmers or students with at least one + term of Python programming experience learn the basics of the C++ programming language.
+This book is written using the build on what you know + philosophy. In order to help you learn C++ we will start with a Python + example and then implement the example in C++. We will also + examine the strengths, weaknesses, and differences between these two + languages. As such, this book does not attempt to replace the many good C++ reference books + that are available. Please feel free to use this book for + yourself, or as a resource for a course you are teaching.
+This ebook is published using a Creative Commons license to + encourage you to use it, change it, and modify it for your own purposes. + We would appreciate knowing what you think if you do use this book, and we + would love to see any modifications or additions you make. Please, Fork Me!
+Python is a great language for beginning programming for several reasons. + First, the syntax is both sparse and clear. Second, the underlying model of + how objects and variables work is very consistent. Third, you can write + powerful and interesting programs without a lot of work. However, Python + is representative of one kind of language, called a dynamic language. + One might think of Python as being fairly informal. Other + languages, like C, C++, and Java are more formal.
+These other more formal languages have some advantages of their own.
+ First, is speed: For very large programs C and C++ are likely to give you the best
+ performance. Second, is their maintainability. Python
+ requires you to remember certain things. For example if you
+ set variable
In one sense Python is representative of a whole class of interpreted languages,
+ sometimes referred to as scripting languages.
Other scripting languages
+ include Ruby and Perl. C++ is representative of
+ what one might call industrial strength languages. Industrial strength
+ languages are good for projects with several or many people working on the
+ project where being formal and careful about what you do may impact lots
+ of other people. Languages in this category include C, C#, C++, Ada, and Java.
The good news is that learning a second programming language is much easier than learning + your first programming language because you will be able to draw upon your existing knowledge. + Programming languages are likely to regularly change as time passes. + As the field of computer science advances there are likely to be new programming + languages that you will want or need to learn. There are certain features + that most programming languages have in common such as variables, loops, + conditionals, and functions. And there are other language features that are unique. If + you know what is common in most languages, then in learning a new language, you need only + to focus on what is different from the languages you already know.
++++
+- +
+C++ is an enormous language which is very powerful because it is a high-level language that offers low-level features, + but one only needs to learn a small part of the language to write effective code.
+- +
+C++ influenced many programming languages such as C#, Java, and other newer versions of C, so by learning C++, + learning these other languages becomes much easier.
+- +
+C++ is an industrial strength programming language and is very often used today for large systems by large groups of people.
+- +
+C++ is particularly good at interacting directly with computer hardware, making execution very fast.
+- +
+C++ was the first widely used object-oriented programming (OOP) language, + supporting the four primary features of OOP: + abstraction, inheritance, polymorphism, and encapsulation.
+- +
+C++ allows the programmer to create and use a data type called a pointer explicitly, + which can increase control over both memory and performance under certain circumstances.
+- +
+Because C++ is fast, it is currently the language of choice for virtual reality.
+- +
+Also, because C++ is fast, it is the language of choice of many 2D and 3D game engines.
+- +
+For all of the above reasons, even though C++ is an older language, + it is still one of the top listed in job advertisements.
+
Turtles are a large tool, and thus have a lot of options dictating how they function.
+ Some features and functionality are more complicated than others, relating to the inner workings
+ of turtles themselves. A few of these include the
Screen modes dictate the direction of angle measurements. This means that, depending on which mode a
Regarding angles, Turtles can use both degrees and radians for their rotations. You can choose between the two using the
+
+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
+screen.tracer(12);
+//Show one out of every 12 frames of animation.
+This can be combined with the
+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
+
Consider the following example and related questions.
+
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main(){
+ ct::TurtleScreen screen;
+ ct::Turtle turtle(screen);
+
+ turtle.speed(ct::TS_FASTEST);
+ screen.tracer(6);
+
+ for(int i = 0; i < 3; i++){
+ turtle.right(60);
+ turtle.forward(50);
+ }
+
+ screen.bye();
+
+ return 0;
+}
+Similarly to tracer settings, every action a turtle takes is also added to the undo queue. This allows it to keep track
+ of actions it is performing over a period of time. The queue is only allowed to grow to a certain size, starting at 100 actions total.
+ This is modifiable through the undo
tool available in most text editors.
+ Turtles can undo
their progress with the
How many frames of animation does the above code create?
+ +3
+Incorrect! Consider how many actions the turtle takes in the for loop.
+6
+Incorrect! Consider the tracer setting for the screen.
+1
+Correct!
+12
+Incorrect! Consider how many actions the turtle takes in the for loop.
+How many actions will be in the turtle's undo queue for the code above?
+ +3
+Incorrect! Consider how many actions the turtle takes in the for loop.
+6
+Correct!
+1
+Incorrect! Consider how many actions the turtle takes in the for loop.
+12
+Incorrect! Consider how many actions the turtle takes in the for loop.
+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"};
+ct::Color random = {"random"};
+
+//This works due to the variable above...
+turtle.pencolor(red);
+
+//And so do these.
+turtle.pencolor({"green"});
+turtle.pencolor({"random"});
+Unlike in Python, the world
screen mode like
+ there is in Python. Normally, this would allow you to specify the bounds
of your canvas (e.g, specify minimum
+ and maximum coordinates for your canvas).
Default shapes are also different and somewhat limited in comparison. Python offers six shapes by default, being arrow
, circle
,
+ turtle
, square
, triangle
, and classic
. arrow
, triangle
,
+ indented triangle
, and square
.
There are a few utility methods available in
+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);
+Every basic shape in
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
+ have their first coordinate there.
Using the default
The example code below illustrates how to create your own shape. We use the
+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!
+ +
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main(){
+ ct::TurtleScreen screen;
+ screen.tracer(1, 1000);
+ ct::Turtle turtle(screen);
+
+ ct::Polygon upside_down_triangle = {
+ {0, 0}, //First point
+ {-5, -5}, //Second point
+ {5, -5} //and so on.
+ };
+
+ turtle.shape(upside_down_triangle);
+ turtle.forward(50);
+
+ screen.bye();
+ return 0;
+}
+
+ 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
+ time-saving utility. Stamps can be placed with the
The following code is a full example showing how to combine custom shapes with stamp placement.
+ +
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main(){
+ ct::TurtleScreen screen;
+ screen.tracer(1, 1000);
+ ct::Turtle turtle(screen);
+
+ ct::Polygon upside_down_triangle = {
+ {0, 0}, //First point
+ {-5, -5}, //Second point
+ {5, -5} //and so on.
+ };
+
+ turtle.shape(upside_down_triangle);
+
+ //Draw a square where each edge is 50 units long.
+ for(int i = 0; i < 4; i++){
+ //Stamp at the corner of the square.
+ int corner_stamp = turtle.stamp();
+
+ turtle.forward(25);
+ turtle.stamp(); //Stamp half-way across the edge of the square.
+ turtle.forward(25);
+
+ turtle.right(90);
+ //Clear the corner stamp.
+ turtle.clearstamp(corner_stamp);
+ }
+
+ turtle.clearstamps();
+
+ screen.bye();
+ return 0;
+}
+
+ Moves the turtle backwards a specified number of units.
+ +Begins to fill the shape indicated by the path the turtle takes after calling it.
+ +Adds a delay at the end of the frame.
+ +Finishes filling the shape the turtle has outlined since calling
Tells the turtle what collor to fill the object it is drawing.
+ +Tells the turtle to go forward a certin number of units.
+ +Moves the turtle to a specified coordinate on the canvas.
+ +Turns the turtle to the left a specified number of units.
+ +Tells the turtle what color it will draw the outline as.
+ +Tells the turtle to pick up its paintbrush.
+ +Tells the turtle to put its paintbrush down.
+ +Turns the turtle to the right a specified number of units.
+ +Tells the turtle how fast to draw.
+ +A queue of actions the turtle has previously taken.
+ +Tells the turtle how wide its paintbrush should be.
+ +Tells the turtle to write text at its current position.
+ +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
+ interpretation of the code itself.
This difference is what allows C++ to be as fast as it is, which also makes it particularly good
+ for graphically-intensive applications. Graphical applications heavily leverage memory management
+ to display every pixel you see on your screen. Python does not allow for the creation of arrays like in
+ C++, which are just chunks
of memory of a fixed size. Furthermore, running directly on the hardware
+ 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.
Turtle graphics are a popular and simple way for introducing programming to beginners. + It was part of the original Logo programming language developed by + Wally Feurzeig, Seymour Papert, and Cynthia Solomon in 1967.
+Imagine turtles as being a digital marker used for drawing various shapes, images, and designs. + Drawing with Turtles can be as basic as a simple triangle and as complex as a highly detailed fractal image. + Nearly all commands used when drawing with Turtles are as simple as telling your Turtle to move forward, backward, + left, and right in as few or many steps as desired.
+The
Python is particularly well-suited for educational purposes due to its
+ wide array of built in tools and good documentation. These things are particularly
+ lacking in regards to C++, as many of the built-in tools require complicated syntax
+ and deep understanding of the language itself. One of these tools is the
Visual representations afford students an opportunity to observe a facet of computer science + from an alternative point of view: rather than waiting anxiously for the print statement + to come around after your program churns, you get a visual representation of the concept itself. + This is particularly useful for abstract concepts such as recursion and iteration.
+For C++, a library called
Below is a comparison of the two versions, C++ and Python, which do + the same thing. Try running both and comparing how the code looks between the two versions.
+ +
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ ct::TurtleScreen scr;
+ ct::Turtle turtle(scr);
+ turtle.speed(ct::TS_SLOWEST);
+ turtle.fillcolor({"purple"});
+ turtle.begin_fill();
+ for (int i = 0; i < 4; i++) {
+ turtle.forward(50);
+ turtle.right(90);
+ }
+ turtle.end_fill();
+ scr.bye();
+ return 0;
+}
+
+
+import turtle
+
+turt = turtle.Turtle()
+turt.fillcolor("purple")
+turt.speed("slowest")
+
+turt.begin_fill()
+for i in range(4):
+ turt.forward(50)
+ turt.right(90)
+turt.end_fill()
+
+ How might students benefit from having a visual representation such as C-Turtle? Check all that apply.
+ +Students receive instant feedback and gratification for their work.
+Correct!
+Students will pay less attention to how their code works, and more attention to its end result.
+Incorrect, because equal thought must be put into the usage of Turtles as well as the outcome.
+Students get more acquainted with RGB values common in web development.
+Incorrect, because RGB values are not the focus or reason behind using Turtles.
+Students will be more comfortable working with concepts they are used to, such as Turtles.
+Correct!
+Art takes a variety of forms, ranging from abstract to realistic, + and consisting of an impossibly wide variety of materials. + Ancient Sumerians would dye and dry small pieces of clay to create mosaics. + These mosaics were often composed of shapes and patterns that would overlap + 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.
+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. + Turtles are one of many such digital mediums, and are often used to + create images rich in repetitive features. Your task will be to create + a mosaic-like tessellating image using turtles.
+Consider the following examples.
+ +
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ const int SQUARE_SIZE = 35;
+
+ ct::TurtleScreen scr;
+ scr.tracer(0);//disable animation
+ ct::Turtle turtle(scr);
+ turtle.speed(ct::TS_FASTEST);
+ turtle.penup();
+
+ for(int i = 0; i < 8; i++){
+ turtle.goTo(-scr.window_width()/2,-scr.window_height()/2+ (i*SQUARE_SIZE)+SQUARE_SIZE);
+
+ bool is_blue = i % 2 == 0;//even (true) or odd (false) row?
+
+ for(int j = 0; j < 8; j++){
+ ct::Color color;
+
+ if(is_blue){
+ color = {"blue"};
+ }else{
+ color = {"orange"};
+ }
+
+ turtle.begin_fill();
+ turtle.fillcolor(color);
+
+ for(int i = 0; i < 4; i++){
+ turtle.forward(SQUARE_SIZE);
+ turtle.right(90);
+ }
+
+ turtle.end_fill();
+
+ turtle.forward(SQUARE_SIZE);
+ is_blue = !is_blue;//flip-flop between true and false
+ }
+ }
+
+ scr.bye();
+ return 0;
+}
+
+
+import turtle
+
+SQUARE_SIZE = 35
+
+wn = turtle.Screen()
+wn.tracer(0);
+square = turtle.Turtle()
+square.speed(10)
+square.pu()
+square.goto(-turtle.window_width()/2,turtle.window_height()/2);
+square.pd()
+
+a = 0
+b = 0
+for i in range(8):
+ if(b == 0):
+ a=1
+ else:
+ a=0
+ for j in range(8):
+ square.penup()
+ square.goto(-turtle.window_width() / 2 + j * SQUARE_SIZE, (-turtle.window_height() / 2) + i * SQUARE_SIZE + SQUARE_SIZE)
+ square.pendown()
+ if(a==0):
+ square.fillcolor('orange')
+ a=1
+ else:
+ square.fillcolor('blue')
+ a=0
+ square.begin_fill()
+ for k in range(4):
+ square.forward(SQUARE_SIZE)
+ square.right(90)
+ square.end_fill()
+ if(b==0):
+ b=1
+ else:
+ b=0
+wn.tracer(1)
+
+ You must create a similar image with the following criteria:
+There must not be four edges in your chosen shape, but 3 or 5+ is fine.
+There must be no more than two colors for the shapes in the image.
+
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ ct::TurtleScreen scr;
+ scr.tracer(0);//disable animation
+ ct::Turtle turtle(scr);
+
+ //Your code here
+
+ scr.bye();
+ return 0;
+}
+
+ Turtles, originally from the Logo programming language, is used as an educational tool. It relates to a conceptual turtle
that runs around on a canvas and draws things.
Python's turtle is a great way to start coding, and until recently, C++ did not have the capability of such a library due to the complexity and required understanding of its syntax.
+Turtles have a variety of commands that are self-describing such as forward
or back
. Almost everything that was available to use in Python for Turtles is also available in C++.
The two versions of the Turtle library differ mainly in syntax, such as differences in entering color codes, and the limited variety of preset shapes available in C++. However, C++ has a few extra utilities not available in Python.
+Turtles provide methods to alter their inner workings, including some control over how many frames of animation are shown with
Every shape created and used by Turtles are a set of coordinates. We can change the shape of our turtles by using the
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.
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ ct::TurtleScreen scr;
+ ct::Turtle turtle(scr);
+
+ turtle.begin_fill();
+
+ for(int i = 0; i < 4; i++){
+ turtle.forward(50);
+ turtle.right(90);
+ }
+
+ turtle.end_fill();
+
+ scr.bye();
+ return 0;
+}
+
+ How large would the undo queue be for the above code example?
+ +13
+No, think about how many times fill is used...
+10
+Correct!
+8
+Incorrect! Consider that almost everything a turtle does is an action, even filling.
+4
+Incorrect! Consider that there are some actions in a for loop.
+
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ ct::TurtleScreen scr;
+ ct::Turtle turtle(scr);
+
+ for(int i = 0; i < 5; i++){
+ turtle.forward(50);
+ turtle.right(144);
+ }
+
+ scr.bye();
+ return 0;
+}
+What kind of shape does the above activecode create?
+ +Circle
+Incorrect! Consider how many times the for-loop iterates...
+No shape
+Incorrect! The turtle's pen is always down.
+Pentagon
+Incorrect! Consider the angle the turtle turns every iteration.
+Star
+Correct!
+You can have more than one turtle on one screen.
+ +True
+Correct!
+False
+Incorrect!
+Turtles must exist on a
+ct::TurtleScreen screen;
+ct::Turtle turtle(screen);
+//Notice how the Screen is given to our Turtle when we create it.
+Closing a
+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
Many of these methods are used alongside one-another to create different images. All of the Turtle Speed
.
Consider the following annotated example.
+ +
+#include <CTurtle.hpp>
+namespace ct = cturtle;
+
+int main() {
+ //Create a turtle screen, and add our turtle to it.
+ ct::TurtleScreen screen;
+ ct::Turtle turtle(screen);
+
+ //Set the turtle speed to the slowest available option.
+ turtle.speed(ct::TS_SLOWEST);
+ //Any number from 0 to 10 would work as well.
+ //turtle.speed(7);
+
+ //Sets the turtle's fill color to purple.
+ turtle.fillcolor({"purple"});
+
+ //Tells the turtle to begin filling a shape as it moves.
+ turtle.begin_fill();
+
+ //Tells the turtle to make a square.
+ //Iterates once for every corner of the square.
+ for (int i = 0; i < 4; i++) {
+
+ //Tells the turtle to move forward 50 units.
+ turtle.forward(50);
+
+ //Tells the turtle to turn 90 degrees to the right.
+ turtle.right(90);
+ }
+
+ //Tells the turtle to finish filling the shape it has outlined.
+ turtle.end_fill();
+
+ //Closes the turtle screen.
+ screen.bye();
+ return 0;
+}
+
+ 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 + familiar. If not, don't worry! It will all be covered in this chapter.
+The order of operations given to a turtle is important, as some actions must be completed
+ one after another. A good example of this is the
Construct a program that fills a green triangle using begin_fill and end_fill + using the example code above as a guide.
+There are 14 commonly used methods for Turtles. Many of them have names that indicate what they do. + See if you can match each method description with their names!
+ +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.
This file allows you to create custom assignments for your class. You write this file + using any valid restructuredText, including the directives that are used in the book. + For example if you want to have a homework problem where the students do some coding + you can do this:
+Write a program that counts from 1 to 10
+
+# your code here
+
+
+ This book was authored in
+
+ + This work is licensed under the open source Creative Commons Attribution-ShareAlike 4.0 International License. To view a copy of this license, visit +
+ 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. +
+