├── _sources ├── _static │ ├── .gitignore │ ├── clock.png │ ├── close.png │ ├── first.png │ ├── last.png │ ├── next.png │ ├── pause.png │ ├── prev.png │ ├── activecodethumb.png │ └── audio │ │ ├── Example04_Tour01_Line01.mp3 │ │ ├── Example04_Tour01_Line01.wav │ │ ├── Example04_Tour01_Line02.mp3 │ │ ├── Example04_Tour01_Line02.wav │ │ ├── Example04_Tour01_Line03.mp3 │ │ └── Example04_Tour01_Line03.wav ├── .DS_Store ├── Turtles │ ├── cc_polygon.png │ ├── toctree.rst │ ├── summary.rst │ ├── check_yourself.rst │ ├── glossary.rst │ ├── differences.rst │ ├── pattern_application.rst │ ├── introduction.rst │ ├── advanced_features.rst │ └── geometry_shapes_stamps.rst ├── Control_Structures │ ├── .DS_Store │ ├── toctree.rst │ ├── summary.rst │ ├── glossary.rst │ ├── for_loop.rst │ └── while_loop.rst ├── AtomicData │ ├── Figures │ │ ├── cpp_var.png │ │ ├── point3.gif │ │ ├── point3.png │ │ ├── oldpoint2.gif │ │ ├── cpp_variable.gif │ │ ├── new_new_point2.png │ │ ├── new_point_broken.png │ │ └── python_reference.png │ ├── toctree.rst │ └── glossary.rst ├── Input_and_Output │ ├── Figures │ │ ├── Read_Open.jpg │ │ └── Write_Open.jpg │ ├── toctree.rst │ └── glossary.rst ├── Exception_Handling │ ├── toctree.rst │ └── glossary.rst ├── Functions │ ├── toctree.rst │ ├── summary.rst │ └── glossary.rst ├── CollectionData │ ├── toctree.rst │ ├── glossary.rst │ └── UnorderedSet.rst ├── IntroCpp │ ├── toctree.rst │ ├── ArrayIteration.cpp │ ├── welcome.rst │ ├── introduction.rst │ ├── glossary.rst │ └── whylearncpp.rst └── index.rst ├── pretext ├── rs-substitutes.xml ├── GenFigs │ └── .web_assets.pkl ├── Figures │ ├── AtomicData │ │ ├── point3.gif │ │ ├── point3.png │ │ ├── cpp_var.png │ │ ├── oldpoint2.gif │ │ ├── cpp_variable.gif │ │ ├── new_new_point12.png │ │ ├── new_point_broken.png │ │ └── python_reference.png │ ├── Turtles │ │ └── cc_polygon.png │ └── Input_and_Output │ │ ├── Read_Open.jpg │ │ └── Write_Open.jpg ├── index.ptx ├── Exception_Handling │ ├── toctree.ptx │ ├── glossary.ptx │ └── Summary.ptx ├── Control_Structures │ ├── toctree.ptx │ ├── glossary.ptx │ ├── summary.ptx │ ├── for_loop.ptx │ └── while_loop.ptx ├── Functions │ ├── toctree.ptx │ ├── glossary.ptx │ ├── summary.ptx │ └── ArraysAsParameter.ptx ├── IntroCpp │ ├── toctree.ptx │ ├── ArrayIteration.cpp.ptx │ ├── welcome.ptx │ ├── introduction.ptx │ ├── glossary.ptx │ └── whylearncpp.ptx ├── AtomicData │ ├── toctree.ptx │ ├── AtomicData.ptx │ ├── UsingDataInCpp.ptx │ ├── glossary.ptx │ ├── CharactersData.ptx │ ├── CharacterData.ptx │ └── CheckYourself.ptx ├── CollectionData │ ├── toctree.ptx │ ├── Collection.ptx │ ├── glossary.ptx │ └── summary.ptx ├── Input_and_Output │ ├── StreamsAsParameter.ptx │ ├── FileHandling.ptx │ ├── toctree.ptx │ ├── MemberFunctionAndPrecision.ptx │ ├── ReadingAndWritingWithFileStream.ptx │ ├── glossary.ptx │ ├── FileNameAndCString.ptx │ ├── DealingWithIOFailures.ptx │ ├── PuttingItAllTogether.ptx │ ├── FileOperations.ptx │ └── Summary.ptx ├── Turtles │ ├── toctree.ptx │ ├── differences.ptx │ ├── glossary.ptx │ └── pattern_application.ptx ├── assignments.ptx ├── main.ptx └── bookinfo.ptx ├── requirements.txt ├── LICENSE.txt ├── pull_request_template.md ├── project.ptx ├── publication ├── runestone.ptx └── publication.ptx ├── old-project.ptx ├── README.rst ├── theBook ├── whylearncpp.rst └── conditionals.rst ├── .gitignore ├── codechat_config.yaml ├── pavement.py └── Makefile /_sources/_static/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pretext/rs-substitutes.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /_sources/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/.DS_Store -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | runestone>=3.2.11 2 | SQLAlchemy>=1.0.8 3 | jupyterlite-sphinx 4 | pretext=2.18.0 -------------------------------------------------------------------------------- /_sources/_static/clock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/clock.png -------------------------------------------------------------------------------- /_sources/_static/close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/close.png -------------------------------------------------------------------------------- /_sources/_static/first.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/first.png -------------------------------------------------------------------------------- /_sources/_static/last.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/last.png -------------------------------------------------------------------------------- /_sources/_static/next.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/next.png -------------------------------------------------------------------------------- /_sources/_static/pause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/pause.png -------------------------------------------------------------------------------- /_sources/_static/prev.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/prev.png -------------------------------------------------------------------------------- /_sources/Turtles/cc_polygon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/Turtles/cc_polygon.png -------------------------------------------------------------------------------- /pretext/GenFigs/.web_assets.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/GenFigs/.web_assets.pkl -------------------------------------------------------------------------------- /_sources/Control_Structures/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/Control_Structures/.DS_Store -------------------------------------------------------------------------------- /_sources/_static/activecodethumb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/activecodethumb.png -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/point3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/point3.gif -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/point3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/point3.png -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/cpp_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/cpp_var.png -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/point3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/point3.gif -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/point3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/point3.png -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/cpp_var.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/cpp_var.png -------------------------------------------------------------------------------- /pretext/Figures/Turtles/cc_polygon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/Turtles/cc_polygon.png -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/oldpoint2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/oldpoint2.gif -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/oldpoint2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/oldpoint2.gif -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/cpp_variable.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/cpp_variable.gif -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/cpp_variable.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/cpp_variable.gif -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/new_new_point2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/new_new_point2.png -------------------------------------------------------------------------------- /_sources/Input_and_Output/Figures/Read_Open.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/Input_and_Output/Figures/Read_Open.jpg -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/new_new_point12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/new_new_point12.png -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/new_point_broken.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/new_point_broken.png -------------------------------------------------------------------------------- /pretext/Figures/AtomicData/python_reference.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/AtomicData/python_reference.png -------------------------------------------------------------------------------- /pretext/Figures/Input_and_Output/Read_Open.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/Input_and_Output/Read_Open.jpg -------------------------------------------------------------------------------- /pretext/Figures/Input_and_Output/Write_Open.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/pretext/Figures/Input_and_Output/Write_Open.jpg -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/new_point_broken.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/new_point_broken.png -------------------------------------------------------------------------------- /_sources/AtomicData/Figures/python_reference.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/AtomicData/Figures/python_reference.png -------------------------------------------------------------------------------- /_sources/Input_and_Output/Figures/Write_Open.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/Input_and_Output/Figures/Write_Open.jpg -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line01.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line01.mp3 -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line01.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line01.wav -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line02.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line02.mp3 -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line02.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line02.wav -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line03.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line03.mp3 -------------------------------------------------------------------------------- /_sources/_static/audio/Example04_Tour01_Line03.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pearcej/cpp4python/HEAD/_sources/_static/audio/Example04_Tour01_Line03.wav -------------------------------------------------------------------------------- /pretext/index.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /_sources/AtomicData/toctree.rst: -------------------------------------------------------------------------------- 1 | Atomic C++ Data Types 2 | ::::::::::::::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | AtomicData.rst 8 | glossary.rst 9 | -------------------------------------------------------------------------------- /_sources/Input_and_Output/toctree.rst: -------------------------------------------------------------------------------- 1 | Input and Output 2 | :::::::::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | InputandOutput.rst 8 | glossary.rst 9 | -------------------------------------------------------------------------------- /_sources/Exception_Handling/toctree.rst: -------------------------------------------------------------------------------- 1 | Exception Handling 2 | :::::::::::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | ExceptionHandling.rst 8 | glossary.rst 9 | -------------------------------------------------------------------------------- /_sources/Functions/toctree.rst: -------------------------------------------------------------------------------- 1 | Functions 2 | ::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | DefiningFunctions.rst 8 | summary.rst 9 | glossary.rst 10 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 2 | 4.0 International License. To view a copy of this license, 3 | visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 4 | -------------------------------------------------------------------------------- /_sources/Control_Structures/toctree.rst: -------------------------------------------------------------------------------- 1 | Control Structures 2 | :::::::::::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | conditionals.rst 8 | while_loop.rst 9 | for_loop.rst 10 | summary.rst 11 | glossary.rst 12 | -------------------------------------------------------------------------------- /_sources/CollectionData/toctree.rst: -------------------------------------------------------------------------------- 1 | Collection Data Types 2 | ::::::::::::::::::::: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | 7 | Arrays.rst 8 | Vectors.rst 9 | Strings.rst 10 | HashTables.rst 11 | UnorderedSet.rst 12 | glossary.rst 13 | -------------------------------------------------------------------------------- /_sources/IntroCpp/toctree.rst: -------------------------------------------------------------------------------- 1 | Introduction to C++ for Python Programmers 2 | :::::::::::::::::::::::::::::::::::::::::: 3 | 4 | .. toctree:: 5 | :caption: Introduction to C++ for Python Programmers 6 | :maxdepth: 2 7 | 8 | welcome.rst 9 | introduction.rst 10 | whylearncpp.rst 11 | firstcppprogram.rst 12 | glossary.rst 13 | -------------------------------------------------------------------------------- /pretext/Exception_Handling/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exception Handling 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /pretext/Control_Structures/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Control Structures 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Description 4 | 5 | 6 | ## Related Issue 7 | 8 | 9 | 10 | 11 | ## How Has This Been Tested? 12 | 13 | -------------------------------------------------------------------------------- /_sources/Turtles/toctree.rst: -------------------------------------------------------------------------------- 1 | Graphics in C++ 2 | :::::::::::::::::::::::::::::::::::::::::: 3 | 4 | .. toctree:: 5 | :caption: Introduction to Turtles for C++ 6 | :maxdepth: 2 7 | 8 | introduction.rst 9 | turtle_and_turtlescreen.rst 10 | geometry_shapes_stamps.rst 11 | advanced_features.rst 12 | differences.rst 13 | pattern_application.rst 14 | summary.rst 15 | check_yourself.rst 16 | glossary.rst 17 | 18 | .. The glossary page has the matching content as well. -------------------------------------------------------------------------------- /_sources/IntroCpp/ArrayIteration.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int nums[] = {1,3,6,2,5}; 6 | int numsSize = sizeof(nums)/sizeof(nums[0]); // Get size of the nums array 7 | 8 | for (int index=0; index 2 | 3 | Functions 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /pretext/IntroCpp/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Introduction to C++ for Python Programmers 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /pretext/AtomicData/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Atomic C++ Data Types 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /_sources/Control_Structures/summary.rst: -------------------------------------------------------------------------------- 1 | Summary 2 | ======= 3 | 1. Like Python C++ also supports the ``if-else`` conditional statements, and they behave the same way as they do in a Python program. 4 | 2. Unlike Python, C++ does not support the use of the ``elif`` statement. However, you can get the functionality of an ``elif`` statement by nesting ``if`` and ``else`` statements in C++. 5 | 3. C++ also supports a ``switch`` statement that acts something like the elif statement of Python under certain conditions. 6 | 4. C++ supports the use of Boolean expressions in ``if-else`` statements. 7 | -------------------------------------------------------------------------------- /pretext/CollectionData/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Collection Data Types 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /pretext/CollectionData/Collection.ptx: -------------------------------------------------------------------------------- 1 |
2 | Collections 3 |

In addition to the numeric, Boolean, and character types, 4 | C++ also offers built-in collection types. 5 | A collection data type is a grouping of some number of other data items 6 | (possibly only zero or one) that have some shared significance 7 | or need to be operated upon together.

8 |

Arrays, vectors, strings, sets, and hash tables are among these useful 9 | C++ collection types.

10 |
11 | 12 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/StreamsAsParameter.ptx: -------------------------------------------------------------------------------- 1 |
2 | Passing Streams as Parameters 3 |

In the above program, you see that the input and output streams are passed to the file 4 | via pass by reference. This fact may at first seem like a surprising choice 5 | until you realize that a stream must be changed in order to read from it or write to it. 6 | In other words, as streams flow, they are changed. 7 | For this reason, all streams will always be passed by reference.

8 |
9 | 10 | -------------------------------------------------------------------------------- /pretext/Turtles/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Graphics in C++ 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /pretext/assignments.ptx: -------------------------------------------------------------------------------- 1 | 2 |
3 | Class Assignments 4 |

This file allows you to create custom assignments for your class. You write this file 5 | using any valid restructuredText, including the directives that are used in the book. 6 | For example if you want to have a homework problem where the students do some coding 7 | you can do this:

8 |

Write a program that counts from 1 to 10

9 | 10 | 11 | # your code here 12 | 13 | 14 |
15 | -------------------------------------------------------------------------------- /_sources/Functions/summary.rst: -------------------------------------------------------------------------------- 1 | Summary 2 | ======== 3 | 1. Like Python, C++ supports the use of functions. 4 | 2. In C++, a function definition requires a name, a group of parameters, a return type, and a body. 5 | 3. Non-fruitful functions in C++ must contain the keyword ``void`` in its function definition. 6 | 4. You can pass variables by value as well as by reference in C++ functions. Passing by reference utilizes the use of pointers. 7 | 5. Pass by reference is useful when you require a function to return multiple variables. 8 | 6. 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 ]). 9 | -------------------------------------------------------------------------------- /pretext/AtomicData/AtomicData.ptx: -------------------------------------------------------------------------------- 1 |
2 | Using Data in C++ 3 |

C++ requires the users specify the specific data type of each variable 4 | before it is used. 5 | The primary C++ built-in atomic data types are: integer (int), 6 | floating point (float), double precision floating point (double), 7 | Boolean (bool), and character (char). There is also a special 8 | type which holds a memory location called pointer. C++ also has 9 | collection or compound data types, which will be discussed in a future 10 | chapter.

11 |
12 | 13 | -------------------------------------------------------------------------------- /pretext/AtomicData/UsingDataInCpp.ptx: -------------------------------------------------------------------------------- 1 |
2 | Using Data in C++ 3 |

C++ requires the users specify the specific data type of each variable 4 | before it is used. 5 | The primary C++ built-in atomic data types are: integer (int), 6 | floating point (float), double precision floating point (double), 7 | Boolean (bool), and character (char). There is also a special 8 | type which holds a memory location called pointer. C++ also has 9 | collection or compound data types, which will be discussed in a future 10 | chapter.

11 |
12 | 13 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/FileHandling.ptx: -------------------------------------------------------------------------------- 1 |
2 | File Handling 3 |

File handling in C++ also uses a stream in a similar way to the cout and cin functions of <iostream>. The library that allows for input and output of files is <fstream>.

4 |

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 in_stream that is an input-file-stream object, <ifstream>, and another called out_stream that is an output-file-stream object, <ofstream>.

5 |
ifstream in_stream;
6 | ofstream out_stream;
7 |
8 | 9 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/toctree.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | Input and Output 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /pretext/main.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | C++ for Python Programmers 7 | The PreTeXt Edition 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /project.ptx: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 14 | 15 | 20 | 21 | 25 | 26 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/MemberFunctionAndPrecision.ptx: -------------------------------------------------------------------------------- 1 |
2 | Member Functions and Precision 3 |

A function that is associated with a certain type of object is called a member function of that object. You have already used member functions setf(...) and precision(...) for formatting our output streams using cout. These functions are included briefly below:

4 |
// Use cout's member function "set flags", called setf
 5 | // The argument here means to use a fixed point rather than scientific notation
 6 | cout.setf(ios::fixed);
 7 | 
 8 | // Use cout's setf function again, but this time
 9 | // The argument tells cout to show the decimal point
10 | cout.setf(ios::showpoint);
11 | 
12 | // Use cout's member function, called Precision
13 | // The argument indicated to display 2 digits of precision
14 | cout.precision(2);
15 |
16 | 17 | -------------------------------------------------------------------------------- /pretext/IntroCpp/ArrayIteration.cpp.ptx: -------------------------------------------------------------------------------- 1 | <script type="text/javascript">function CodeChat_doStyle(element) {function walk_tree(elements,func_walk,func_child) {let walk_children = [];for (let index = 0; index < elements.length; ++index) {let that = elements[index];while (that && !func_walk(that)) {that = that.parentElement;}if (that) {that = func_walk(that);walk_children.push(that);while (that && func_child(that)) {that = func_child(that);walk_children.push(that);}}}return walk_children;};element = (typeof element !== 'undefined') ? element : document;let code = element.getElementsByClassName("fenced-code");walk_tree(code, x => x.nextElementSibling, x => x.firstElementChild).map(x =>x.classList.add('CodeChat_noTop'));walk_tree(code, x => x.previousElementSibling, x => x.lastElementChild).map(x =>x.classList.add('CodeChat_noBottom'));}document.addEventListener("DOMContentLoaded", function(event) { CodeChat_doStyle(); });</script> 2 | 3 | -------------------------------------------------------------------------------- /_sources/IntroCpp/welcome.rst: -------------------------------------------------------------------------------- 1 | Welcome to *C++ for Python Programmers* 2 | ======================================= 3 | 4 | This short ebook is intended to help Python programmers or students with at least one 5 | term of Python programming experience learn the basics of the C++ programming language. 6 | 7 | This book is written using the build on what you know 8 | philosophy. In order to help you learn C++ we will start with a Python 9 | example and then implement the example in C++. We will also 10 | examine the strengths, weaknesses, and differences between these two 11 | languages. As such, this book does not attempt to replace the many good C++ reference books 12 | that are available. Please feel free to use this book for 13 | yourself, or as a resource for a course you are teaching. 14 | 15 | This ebook is published using a Creative Commons license to 16 | encourage you to use it, change it, and modify it for your own purposes. 17 | We would appreciate knowing what you think if you do use this book, and we 18 | would love to see any modifications or additions you make. Please, Fork Me! 19 | -------------------------------------------------------------------------------- /_sources/Turtles/summary.rst: -------------------------------------------------------------------------------- 1 | Summary 2 | ======= 3 | 4 | - 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. 5 | - 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. 6 | - 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++. 7 | - 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. 8 | - Turtles provide methods to alter their inner workings, including some control over how many frames of animation are shown with :code:`tracer` method. 9 | - Every shape created and used by Turtles are a set of coordinates. We can change the shape of our turtles by using the :code:`shape` method to one of four default shapes, or by manually entering coordinates and creating your own. 10 | -------------------------------------------------------------------------------- /_sources/IntroCpp/introduction.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | This book assumes that you are already familiar with the 5 | `Python `_ programming language because 6 | Python will be the starting point for our journey into C++. We will begin by 7 | looking at a very simple C++ program to see how the C++ language 8 | looks, and we will discuss how we get a C++ program to run. 9 | 10 | Next, we will look at the primary constructs that are common 11 | to nearly all programming languages: 12 | 13 | - Using code libraries 14 | 15 | - Documenting with comments 16 | 17 | - The main function 18 | 19 | - Writing output to the screen 20 | 21 | - Reading input from the keyboard 22 | 23 | - Data types and operators 24 | 25 | - Conditionals 26 | 27 | - Loops 28 | 29 | Once we have the basics of C++ behind us we will move on to look at the 30 | additonal useful features of C++ including: 31 | 32 | - Functions and their parameters 33 | 34 | - File operations 35 | 36 | - Exception handling 37 | 38 | Please note that this book is a work in progress. 39 | Updates and new versions are likely to be forthcoming. 40 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/ReadingAndWritingWithFileStream.ptx: -------------------------------------------------------------------------------- 1 |
2 | Reading and Writing with File Streams 3 |

As file I/O streams work in a similar way to cin and cout, the operators >> and << perform the same direction of data for files, with the exact same syntax.

4 |

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.

5 |
out_stream << 25 << endl;
 6 | out_stream << 15 << endl;
7 |

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 inputn.

8 |
int inputn;
 9 | in_stream >> inputn;
10 |
11 | 12 | -------------------------------------------------------------------------------- /pretext/Exception_Handling/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | exception 7 | 8 |

a response to an unusual circumstance while a program is running

9 | 10 |
11 | 12 | logic error 13 | 14 |

an error in which the program/code functions, but performs incorrectly

15 | 16 |
17 | 18 | runtime error 19 | 20 |

an error that occurs when a program runs

21 | 22 |
23 | 24 | syntax error 25 | 26 |

an error in the structure of a statement or expression of code

27 | 28 |
29 | 30 |
31 |
32 | 33 | -------------------------------------------------------------------------------- /pretext/IntroCpp/welcome.ptx: -------------------------------------------------------------------------------- 1 |
2 | Welcome to <em>C++ for Python Programmers</em> 3 |

This short ebook is intended to help Python programmers or students with at least one 4 | term of Python programming experience learn the basics of the C++ programming language.

5 |

This book is written using the build on what you know 6 | philosophy. In order to help you learn C++ we will start with a Python 7 | example and then implement the example in C++. We will also 8 | examine the strengths, weaknesses, and differences between these two 9 | languages. As such, this book does not attempt to replace the many good C++ reference books 10 | that are available. Please feel free to use this book for 11 | yourself, or as a resource for a course you are teaching.

12 |

This ebook is published using a Creative Commons license to 13 | encourage you to use it, change it, and modify it for your own purposes. 14 | We would appreciate knowing what you think if you do use this book, and we 15 | would love to see any modifications or additions you make. Please, Fork Me!

16 |
17 | 18 | -------------------------------------------------------------------------------- /_sources/Exception_Handling/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | exception 10 | a response to an unusual circumstance while a program is running 11 | 12 | logic error 13 | an error in which the program/code functions, but performs incorrectly 14 | 15 | runtime error 16 | an error that occurs when a program runs 17 | 18 | syntax error 19 | an error in the structure of a statement or expression of code 20 | 21 | 22 | Matching 23 | -------- 24 | .. dragndrop:: matching_ch7 25 | :feedback: Feedback shows incorrect matches. 26 | :match_1: exception|||Response to an unusual circumstance while a program is running. 27 | :match_2: logic error|||Error in which the program/code functions, but performs incorrectly. 28 | :match_3: runtime error|||Error that occurs when a program encounters an issue during its execution. 29 | :match_4: syntax error|||Error in the structure of a statement or expression of code. 30 | 31 | 32 | Match the words with their corresponding definition. 33 | -------------------------------------------------------------------------------- /publication/runestone.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | c-string 7 | 8 |

An array of characters that ends with a terminating null character. i.e. \0.

9 | 10 |
11 | 12 | member function 13 | 14 |

A function that's associated with a certain type of object; this function is called a member function of that object.

15 | 16 |
17 | 18 | stream 19 | 20 |

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.

21 | 22 |
23 | 24 | End-Of-File(EOF) 25 | 26 |

A flag at the end of the file to let programs know when to stop.

27 | 28 |
29 | 30 |
31 |
32 | 33 | -------------------------------------------------------------------------------- /_sources/Input_and_Output/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | 10 | c-string 11 | An array of characters that ends with a terminating null character. i.e. ``\0``. 12 | 13 | member function 14 | A function that's associated with a certain type of object; this function is called a member function of that object. 15 | 16 | stream 17 | 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. 18 | 19 | End-Of-File(EOF) 20 | A flag at the end of the file to let programs know when to stop. 21 | 22 | 23 | Matching 24 | -------- 25 | .. dragndrop:: matching_ch6 26 | :feedback: Feedback shows incorrect matches. 27 | :match_1: stream|||An abstraction that allows you to send or receive an unknown number of bytes in input or output. 28 | :match_2: member function|||A function that's associated with a certain type of object. 29 | :match_3: c-string||| An array of characters that ends with a terminating null character. 30 | :match_4: End-Of-File|||A flag that lets programs know when to stop. 31 | 32 | Match the words to thier corresponding definition. -------------------------------------------------------------------------------- /publication/publication.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /_sources/Control_Structures/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | 10 | ``break`` 11 | Terminates the current block of code and resumes the program outside of it. 12 | 13 | ``case`` 14 | A condition in a switch statement for a variable to be tested against. 15 | 16 | conditional 17 | A statement that tests whether a condition is true or false 18 | 19 | loop 20 | A series of instructions repeated infinitely or until a condition is met. 21 | 22 | ``switch`` 23 | A statement that tests a variable against possible conditions for it. 24 | 25 | 26 | Matching 27 | -------- 28 | .. dragndrop:: matching_ControlStructures 29 | :feedback: Feedback shows incorrect matches. 30 | :match_1: break|||Terminates the current block of code and resumes the program outside of it. 31 | :match_2: case|||Condition in a switch statement for a variable to be tested against. 32 | :match_3: conditional|||Statement that tests whether a condition is true or false . 33 | :match_4: loop|||Series of instructions repeated infinitely or until a condition is met. 34 | :match_5: switch|||Statement that tests a variable against possible conditions for it. 35 | 36 | Drag each glossary term to its' corresponding definition. -------------------------------------------------------------------------------- /pretext/Control_Structures/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | <c>break</c> 7 | 8 |

Terminates the current block of code and resumes the program outside of it.

9 | 10 |
11 | 12 | <c>case</c> 13 | 14 |

A condition in a switch statement for a variable to be tested against.

15 | 16 |
17 | 18 | conditional 19 | 20 |

A statement that tests whether a condition is true or false

21 | 22 |
23 | 24 | loop 25 | 26 |

A series of instructions repeated infinitely or until a condition is met.

27 | 28 |
29 | 30 | <c>switch</c> 31 | 32 |

A statement that tests a variable against possible conditions for it.

33 | 34 |
35 | 36 |
37 |
38 | 39 | -------------------------------------------------------------------------------- /_sources/AtomicData/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | 10 | address-of 11 | the address-of operator (``&``) is used to access the address of a C++ variable. 12 | 13 | atomic data type 14 | basic data type that cannot be broken down into any simpler data elements. 15 | 16 | ``bool`` 17 | keyword for Boolean data type. 18 | 19 | ``char`` 20 | keyword for character data type that stores a single character. 21 | 22 | dereference 23 | follow a pointer to its referenced memory location and read the data there. 24 | 25 | ``float`` 26 | keyword for floating point data type. 27 | 28 | ``double`` 29 | keyword for double-precision floating point data type. 30 | 31 | ``int`` 32 | keyword for integer data type. 33 | 34 | 35 | Matching 36 | -------- 37 | .. dragndrop:: matching_ADT 38 | :feedback: Feedback shows incorrect matches. 39 | :match_1: address-of|||(&) is used to access the memory address of a C++ variable. 40 | :match_2: atomic data type|||Data type that cannot be broken down into any simpler data elements. 41 | :match_3: dereference|||Reads data in a pointers memory location. 42 | :match_4: pointer|||Variables that store and manipulate memory addresses. 43 | 44 | Drag each glossary term to its' corresponding definition. (Note: none of the data types are in this matching, but they are in the glossary) -------------------------------------------------------------------------------- /_sources/Functions/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | 10 | 11 | argument 12 | the data passed to parameter. 13 | 14 | ``const`` 15 | keyword that makes a variable or value constant and unchanging. 16 | 17 | function 18 | a section of code that performs a procedure and is usually named. 19 | 20 | overloading 21 | specifying more than one definition for the same function name within the same scope. 22 | 23 | parameter 24 | a variable in a function or method definition that accepts data passed from an argument. 25 | 26 | pointer 27 | a value that indicates a place in a computer’s memory. 28 | 29 | ``void`` 30 | Keyword indicating a function has no return value. 31 | 32 | 33 | Matching 34 | -------- 35 | .. dragndrop:: matching_Functions 36 | :feedback: Feedback shows incorrect matches. 37 | :match_1: argument|||Data passed to parameter. 38 | :match_2: const|||indicates a variable or value is unchanging. 39 | :match_3: function ||| Section of code that performs a procedure and usually is named meaningfully. 40 | :match_4: overloading|||Specifying more than one definition for the same function name. 41 | :match_5: parameter|||Variable in a function or method definition that accepts data passed from an argument. 42 | :match_6: reference|||Value that indicates an address in a computer’s memory. 43 | :match_7: void|||indicates a function has no return value. 44 | 45 | Drag each glossary term to its' corresponding definition. 46 | -------------------------------------------------------------------------------- /pretext/Functions/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | argument 7 | 8 |

the data passed to parameter.

9 | 10 |
11 | 12 | <c>const</c> 13 | 14 |

keyword that makes a variable or value constant and unchanging.

15 | 16 |
17 | 18 | function 19 | 20 |

a section of code that performs a procedure and is usually named.

21 | 22 |
23 | 24 | overloading 25 | 26 |

specifying more than one definition for the same function name within the same scope.

27 | 28 |
29 | 30 | parameter 31 | 32 |

a variable in a function or method definition that accepts data passed from an argument.

33 | 34 |
35 | 36 | pointer 37 | 38 |

a value that indicates a place in a computer's memory.

39 | 40 |
41 | 42 | <c>void</c> 43 | 44 |

Keyword indicating a function has no return value.

45 | 46 |
47 | 48 |
49 | 50 |
51 | 52 | -------------------------------------------------------------------------------- /pretext/Control_Structures/summary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Summary & Reading Questions 3 |

    4 |
  1. 5 |

    Like Python C++ also supports the if-else conditional statements, and they behave the same way as they do in a Python program.

    6 |
  2. 7 |
  3. 8 |

    Unlike Python, C++ does not support the use of the elif statement. However, you can get the functionality of an elif statement by nesting if and else statements in C++.

    9 |
  4. 10 |
  5. 11 |

    C++ also supports a switch statement that acts something like the elif statement of Python under certain conditions.

    12 |
  6. 13 |
  7. 14 |

    C++ supports the use of Boolean expressions in if-else statements.

    15 |
  8. 16 |

17 | 18 | Reading Question 19 | 20 |

Drag each glossary term to its' corresponding definition.

21 |

Feedback shows incorrect matches.

22 | breakTerminates the current block of code and resumes the program outside of it.caseCondition in a switch statement for a variable to be tested against.conditionalStatement that tests whether a condition is true or false .loopSeries of instructions repeated infinitely or until a condition is met.switchStatement that tests a variable against possible conditions for it.
23 |
24 | 25 | -------------------------------------------------------------------------------- /_sources/Turtles/check_yourself.rst: -------------------------------------------------------------------------------- 1 | Check Yourself 2 | ============== 3 | 4 | .. activecode:: turtle_checkyourself_ac_1 5 | :language: cpp 6 | 7 | #include 8 | namespace ct = cturtle; 9 | 10 | int main() { 11 | ct::TurtleScreen scr; 12 | ct::Turtle turtle(scr); 13 | 14 | turtle.begin_fill(); 15 | 16 | for(int i = 0; i < 4; i++){ 17 | turtle.forward(50); 18 | turtle.right(90); 19 | } 20 | 21 | turtle.end_fill(); 22 | 23 | scr.bye(); 24 | return 0; 25 | } 26 | 27 | .. mchoice:: turtle_checkyourself_mchoice_1 28 | :answer_a: 13 29 | :answer_b: 10 30 | :answer_c: 8 31 | :answer_d: 4 32 | :correct: b 33 | :feedback_a: No, think about how many times fill is used... 34 | :feedback_b: Correct! 35 | :feedback_c: Incorrect! Consider that almost everything a turtle does is an action, even filling. 36 | :feedback_d: Incorrect! Consider that there are some actions in a for loop. 37 | 38 | How large would the undo queue be for the above code example? 39 | 40 | .. code-block:: cpp 41 | 42 | #include 43 | namespace ct = cturtle; 44 | 45 | int main() { 46 | ct::TurtleScreen scr; 47 | ct::Turtle turtle(scr); 48 | 49 | for(int i = 0; i < 5; i++){ 50 | turtle.forward(50); 51 | turtle.right(144); 52 | } 53 | 54 | scr.bye(); 55 | return 0; 56 | } 57 | 58 | .. mchoice:: turtle_checkyourself_mchoice_2 59 | :answer_a: Circle 60 | :answer_b: No shape 61 | :answer_c: Pentagon 62 | :answer_d: Star 63 | :correct: d 64 | :feedback_a: Incorrect! Consider how many times the for-loop iterates... 65 | :feedback_b: Incorrect! The turtle's pen is always down. 66 | :feedback_c: Incorrect! Consider the angle the turtle turns every iteration. 67 | :feedback_d: Correct! 68 | 69 | What kind of shape does the above activecode create? 70 | 71 | .. mchoice:: turtle_checkyourself_mchoice_3 72 | :answer_a: True 73 | :answer_b: False 74 | :correct: a 75 | :feedback_a: Correct! 76 | :feedback_b: Incorrect! 77 | 78 | You can have more than one turtle on one screen. 79 | -------------------------------------------------------------------------------- /_sources/Turtles/glossary.rst: -------------------------------------------------------------------------------- 1 | Glossary 2 | ======================================= 3 | 4 | .. glossary:: 5 | 6 | back 7 | Moves the turtle backwards a specified number of units. 8 | 9 | beginfill 10 | Begins to fill the shape indicated by the path the turtle takes after calling it. 11 | 12 | delay 13 | Adds a delay at the end of the frame. 14 | 15 | endfill 16 | Finishes filling the shape the turtle has outlined since calling :code:`beginfill`. 17 | 18 | fillcolor 19 | Tells the turtle what collor to fill the object it is drawing. 20 | 21 | forward 22 | Tells the turtle to go forward a certin number of units. 23 | 24 | goto 25 | Moves the turtle to a specified coordinate on the canvas. 26 | 27 | left 28 | Turns the turtle to the left a specified number of units. 29 | 30 | pencolor 31 | Tells the turtle what color it will draw the outline as. 32 | 33 | penup 34 | Tells the turtle to pick up its paintbrush. 35 | 36 | pendown 37 | Tells the turtle to put its paintbrush down. 38 | 39 | right 40 | Turns the turtle to the right a specified number of units. 41 | 42 | speed 43 | Tells the turtle how fast to draw. 44 | 45 | undo queue 46 | A queue of actions the turtle has previously taken. 47 | 48 | width 49 | Tells the turtle how wide its paintbrush should be. 50 | 51 | write 52 | Tells the turtle to write text at its current position. 53 | 54 | Matching 55 | ======== 56 | 57 | .. dragndrop:: cturtle_dnd_glossary 58 | :match_1: what color to fill drawing with.|||turtle.fillcolor 59 | :match_2: start filling the shape.|||turtle.beginfill 60 | :match_3: stops filling the shape.|||turtle.endfill 61 | :match_4: change the paintbrush color.|||turtle.pencolor 62 | :match_5: change the paintbrush size.|||turtle.width 63 | :match_6: change the speed|||turtle.speed 64 | :match_7: move backward.|||turtle.back 65 | :match_8: move forward.|||turtle.forward 66 | :match_9: move to a specific coordinate.|||turtle.goto 67 | :match_10: write some text to the canvas.|||turtle.write 68 | 69 | -------------------------------------------------------------------------------- /pretext/AtomicData/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | address-of 7 | 8 |

the address-of operator (&) is used to access the address of a C++ variable.

9 | 10 |
11 | 12 | atomic data type 13 | 14 |

basic data type that cannot be broken down into any simpler data elements.

15 | 16 |
17 | 18 | <c>bool</c> 19 | 20 |

keyword for Boolean data type.

21 | 22 |
23 | 24 | <c>char</c> 25 | 26 |

keyword for character data type that stores a single character.

27 | 28 |
29 | 30 | dereference 31 | 32 |

follow a pointer to its referenced memory location and read the data there.

33 | 34 |
35 | 36 | <c>float</c> 37 | 38 |

keyword for floating point data type.

39 | 40 |
41 | 42 | <c>double</c> 43 | 44 |

keyword for double-precision floating point data type.

45 | 46 |
47 | 48 | <c>int</c> 49 | 50 |

keyword for integer data type.

51 | 52 |
53 | 54 |
55 |
56 | 57 | -------------------------------------------------------------------------------- /_sources/Control_Structures/for_loop.rst: -------------------------------------------------------------------------------- 1 | For Loops 2 | ========= 3 | 4 | Even though the ``while`` type of construct is very useful in a wide variety of 5 | situations, another iterative structure, the ``for`` statement, can be 6 | used to iterate across a range of values easily. 7 | A ``for`` statement allows us to write a loop that is executed a specific number of times. 8 | 9 | .. activecode:: ForLoopIterations 10 | :language: cpp 11 | :sourcefile: ForLoopIterations.cpp 12 | 13 | #include 14 | using namespace std; 15 | 16 | int main() { 17 | for (int i = 0; i < 10; i++){ 18 | cout << i << "hello world" << endl; 19 | } 20 | } 21 | 22 | 23 | 24 | In the example above, the **hello world** statement is executed 10 times. 25 | 26 | A common use of the ``for`` construct is to implement **certain** repetition 27 | over a range of values. 28 | 29 | .. activecode:: rangeForLoop1 30 | :language: cpp 31 | 32 | #include 33 | using namespace std; 34 | 35 | // squares the numebers in range 5 36 | // ex. 0*0, 1*1, 2*2 ... 37 | int main() { 38 | for (int i=0; i<5; i++) { 39 | cout << i*i << " "; 40 | } 41 | 42 | return 0; 43 | } 44 | 45 | 46 | The code will use ``cout`` five times. The value of the variable ``i`` will 47 | start at 0 and go through the full sequence of values 0,1,2,3,4. This 48 | value is then squared and printed. 49 | 50 | 51 | Check yourself 52 | ============== 53 | 54 | :: 55 | 56 | #include 57 | using namespace std; 58 | 59 | int main() { 60 | 61 | for (int counter=0; counter<4; counter++) { 62 | cout << counter * 2 << " "; 63 | } 64 | 65 | return 0; 66 | } 67 | 68 | .. mchoice:: mc_forloop 69 | :answer_a: 0 2 4 6 70 | :answer_b: 0 0 0 0 71 | :answer_c: Runtime error 72 | :answer_d: 0 1 2 3 73 | :answer_e: all of the above 74 | :correct: a 75 | :feedback_a: Good Job! 76 | :feedback_b: Not quite, take another look at the operation happening in the cout line 77 | :feedback_c: Not quite, take another look at the for loop 78 | :feedback_d: Not quite, take another look at the operation happening in the cout line 79 | 80 | Using the code above please select the answer that should appear? 81 | -------------------------------------------------------------------------------- /pretext/IntroCpp/introduction.ptx: -------------------------------------------------------------------------------- 1 |
2 | Introduction 3 |

This book assumes that you are already familiar with the 4 | Python programming language because 5 | Python will be the starting point for our journey into C++. We will begin by 6 | looking at a very simple C++ program to see how the C++ language 7 | looks, and we will discuss how we get a C++ program to run.

8 |

Next, we will look at the primary constructs that are common 9 | to nearly all programming languages:

10 |
11 |

    12 |
  • 13 |

    Using code libraries

    14 |
  • 15 |
  • 16 |

    Documenting with comments

    17 |
  • 18 |
  • 19 |

    The main function

    20 |
  • 21 |
  • 22 |

    Writing output to the screen

    23 |
  • 24 |
  • 25 |

    Reading input from the keyboard

    26 |
  • 27 |
  • 28 |

    Data types and operators

    29 |
  • 30 |
  • 31 |

    Conditionals

    32 |
  • 33 |
  • 34 |

    Loops

    35 |
  • 36 |

37 |
38 |

Once we have the basics of C++ behind us we will move on to look at the 39 | additonal useful features of C++ including:

40 |
41 |

    42 |
  • 43 |

    Functions and their parameters

    44 |
  • 45 |
  • 46 |

    File operations

    47 |
  • 48 |
  • 49 |

    Exception handling

    50 |
  • 51 |

52 |
53 |

Please note that this book is a work in progress. 54 | Updates and new versions are likely to be forthcoming.

55 |
56 | 57 | -------------------------------------------------------------------------------- /pretext/bookinfo.ptx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | cpp4py-v2 28 | 29 | 30 | SB 31 | This is the PreTeXt alpha version of a short ebook that is intended to make it easy for anyone who has some background in programming in Python to transition to programming in C++. This ebook also utilizes an optional graphics module that allows graphics in C++ to utilize commands like the Turtle library in Python. 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /old-project.ptx: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | html 11 | pretext/cpp4python.ptx 12 | pretext/publication-rs-for-all.xml 13 | output/html 14 | 15 | 16 | html 17 | pretext/cpp4python.ptx 18 | pretext/publication-rs-academy.xml 19 | published/cpp4py-v2 20 | 21 | 22 | epub 23 | pretext/cpp4python.ptx 24 | pretext/publication-pub.xml 25 | published/epub 26 | 27 | 28 | latex 29 | pretext/cpp4python.ptx 30 | pretext/publication-rs-for-all.xml 31 | output/latex 32 | 33 | 34 | pdf 35 | pretext/cpp4python.ptx 36 | pretext/publication-rs-for-all.xml 37 | output/pdf 38 | 39 | 40 | html 41 | source/cpp4python.ptx 42 | publication/publication.ptx 43 | output/subset 44 | 45 | 47 | ch-first 48 | 49 | 50 | 51 | latex 52 | pdflatex 53 | xelatex 54 | pdf2svg 55 | asy 56 | sage 57 | convert 58 | pdftops 59 | pdf-crop-margins 60 | pageres 61 | node 62 | file2brl 63 | 64 | 65 | -------------------------------------------------------------------------------- /_sources/Turtles/differences.rst: -------------------------------------------------------------------------------- 1 | Python's turtle vs C-Turtle 2 | ========================================== 3 | 4 | :code:`C-Turtle` varies from the Python :code:`turtle` library primarily in syntax. Most of the methods 5 | are exactly the same between implementations, however there are a few notable differences between the two. 6 | Colors, for example, must be surrounded by curly brackets (e.g, '{' and '}') when referring to them by a 7 | name such as "red", "green", or "blue". You can also ask for a random color by using the string "random". 8 | 9 | .. code-block:: cpp 10 | 11 | ct::Color red = {"red"}; 12 | ct::Color green = {"green"}; 13 | ct::Color blue = {"blue"}; 14 | ct::Color random = {"random"}; 15 | 16 | //This works due to the variable above... 17 | turtle.pencolor(red); 18 | 19 | //And so do these. 20 | turtle.pencolor({"green"}); 21 | turtle.pencolor({"random"}); 22 | 23 | Unlike in Python, the :code:`write` method does not allow you to specify a font nor size. In contrast to Python, C++ finds it much more challenging to handle fonts because operating systems deal with them in a complex way. Furthermore, there is no "world" screen mode like 24 | there is in Python. Normally, this would allow you to specify the "bounds" of your canvas (e.g, specify minimum 25 | and maximum coordinates for your canvas). 26 | 27 | Default shapes are also different and somewhat limited in comparison. Python offers six shapes by default, being "arrow", "circle", 28 | "turtle", "square", "triangle", and "classic". :code:`C-Turtle`, on the other hand, offers four shapes by default: "arrow", "triangle", 29 | "indented triangle", and "square". 30 | 31 | There are a few utility methods available in :code:`C-Turtle` that are not available in Python, such as :code:`shift` and :code:`middle`. 32 | The former of the two, :code:`shift`, simply adds to the X and Y coordinate position of the turtle. If your turtle is at coordinate 33 | 600x, 400y and :code:`shift` is called with coordinate 50x and -50y, the turtle's final position would be 650x, 350y. The latter 34 | of the two, :code:`middle`, returns the point exactly between two other points. See the examples below. 35 | 36 | .. code-block:: cpp 37 | 38 | turtle.goTo(600, 400); 39 | turtle.shift(50, -50); 40 | //Turtle position is now 650x, 350y. 41 | 42 | .. code-block:: cpp 43 | 44 | ct::Point a = {400, 300}; 45 | ct::Point b = {450, 300}; 46 | 47 | //Should equal the point 425x, 300y. 48 | ct::Point middle = ct::middle(a, b); -------------------------------------------------------------------------------- /_sources/CollectionData/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3 | 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 4 | 5 | 6 | Glossary 7 | -------- 8 | 9 | .. glossary:: 10 | 11 | array 12 | 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. 13 | 14 | collection 15 | 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. 16 | 17 | hash table 18 | a collection consisting of key-value pairs with an associated hash function that maps the key to the associated value. 19 | 20 | const (immutable) 21 | unable to be modified. 22 | 23 | non-const (mutable) 24 | the ability of an object to be modified. 25 | 26 | set 27 | An unordered data structure consisting of unique, immutable data values. 28 | 29 | string 30 | A sequential data structure consisting of zero or more characters. 31 | 32 | vector 33 | sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size. 34 | 35 | word 36 | unit of data used by a particular processor design. 37 | 38 | 39 | Matching 40 | -------- 41 | .. dragndrop:: matching_ch5 42 | :feedback: Feedback shows incorrect matches. 43 | :match_1: array|||a data structure consisting of an ordered collection of data elements of identical type in which each element can be identified by an index. 44 | :match_2: collection||| a grouping of a number of data items that have some shared significance or need to be operated upon together. 45 | :match_3: vector|||sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size. 46 | :match_4: hash table|||a collection consisting of key-value pairs with an associated function that maps the key to the associated value. 47 | :match_5: set|||An unordered data structure consisting of unique, immutable data values. 48 | :match_6: string|||A sequential data structure consisting of zero or more characters. 49 | :match_7: word|||unit of data used by a particular processor design. 50 | :match_8: mutability|||able to be modified. 51 | :match_9: immutable|||unable to be modified. 52 | 53 | Match the words to thier corresponding definition. -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | C++ for Python Programmers 2 | ========================== 3 | 4 | This short ebook is intended to make it easy for anyone with at least some background 5 | in Python to transition to programming in C++. 6 | 7 | Portions of this book began as *Java for Python Programmers* by Brad Miller. 8 | These sections were translated to C++ by Jan Pearce and a team of excellent Berea 9 | College students in 2018 and early 2019. Other portions of this book began as 10 | web pages written by Jan Pearce as support for a Berea College C++ programming class. 11 | Still other sections were newly written by Jan Pearce for this ebook. 12 | 13 | Special acknowledgement is due to `Jesse Walker-Schadler `_ who while just a student in the Berea College Data Structures course had a vision of making graphics in C++ as easy as they are in Python both in terms of both syntax and installations. Over the course of two summers, he realized this vision with the creation in `the open source CTurtle library `_ which provides all of the C++ interactive graphics in this textbook. 14 | 15 | How to use and suggest changes to this book 16 | =========================================== 17 | 18 | - The generic version of the original runestone version book is located at `https://runestone.academy/ns/books/published/cpp4python/index.html `_ 19 | - Instructors who wish to use this book go to `https://runestone.academy/ `_ and make an account using *cpp4python* as the base book. 20 | - The PreTeXt version of this book is available as *cpp4py* as well, but it is an alpha version and there are currently labelling errors as of August 2023. Use at your own risk. 21 | - Those wishing to report bugs or suggest improvements can do so at `https://github.com/pearcej/cpp4python/issues `_. 22 | 23 | Licensing 24 | ========= 25 | 26 | .. raw:: html 27 | 28 | 29 | Creative Commons License
31 | 32 | C++ for Python Programmers 33 | by Jan Pearce and Brad Miller is licensed under a 34 | 35 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 36 | -------------------------------------------------------------------------------- /pretext/CollectionData/glossary.ptx: -------------------------------------------------------------------------------- 1 |
2 | Glossary 3 | 4 | 5 | 6 | array 7 | 8 |

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.

9 | 10 |
11 | 12 | collection 13 | 14 |

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.

15 | 16 |
17 | 18 | hash table 19 | 20 |

a collection consisting of key-value pairs with an associated hash function that maps the key to the associated value.

21 | 22 |
23 | 24 | const (immutable) 25 | 26 |

unable to be modified.

27 | 28 |
29 | 30 | non-const (mutable) 31 | 32 |

the ability of an object to be modified.

33 | 34 |
35 | 36 | set 37 | 38 |

An unordered data structure consisting of unique, immutable data values.

39 | 40 |
41 | 42 | string 43 | 44 |

A sequential data structure consisting of zero or more characters.

45 | 46 |
47 | 48 | vector 49 | 50 |

sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.

51 | 52 |
53 | 54 | word 55 | 56 |

unit of data used by a particular processor design.

57 | 58 |
59 | 60 |
61 |
62 | 63 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/FileNameAndCString.ptx: -------------------------------------------------------------------------------- 1 |
2 | File Names and C-Strings 3 |

In modern versions of C++, you can use the <string> library for filenames, 4 | but earlier versions of C++ required the use of C-strings. 5 | The program above will try to open the file called rawdata.txt and 6 | output its results to a file called neat.dat every time it runs, 7 | which is not very flexible. Ideally, the user should be able to enter 8 | filenames that the program will use instead of the same names. 9 | We have previously talked about the char data type that allows users to store 10 | and manipulate a single character at a time. A sequence of characters such as myFileName.dat 11 | can be stored in an array of chars called a c-string, which can be declared as follows:

12 |
// Syntax: char C-string_name[LEN];
13 | // Example:
14 | char filename[16];
15 |

This declaration creates a variable called filename that can hold a string of 16 | length up to 16-1 characters. 17 | The square brackets after the variable name indicate to the compiler the maximum 18 | number of character storage that is needed for the variable. 19 | A \0 or NULL character terminates the C-string, without the system knowing how much of 20 | the array is actually used.

21 |
22 |
23 |
  • 24 | Warnings: 25 | 26 |

      27 |
    1. 28 |

      The number of characters for a c-string must be one greater than the number of actual characters!

      29 |
    2. 30 |
    3. 31 |

      Also, LEN must be an integer number or a declared const int, it cannot be a variable.

      32 |
    4. 33 |

    34 | 35 |
  • 36 |
    37 |
    38 |

    C-strings are an older type of string that was inherited from the C language, and people frequently refer to both types as strings, which can be confusing.

    39 |

    Typically, string from the <string> library should be used in all other cases when not 40 | working with file names or when a modern version of C++ can be used.

    41 |
    42 | 43 | -------------------------------------------------------------------------------- /pretext/Functions/summary.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Summary & Reading Questions 3 |

      4 |
    1. 5 |

      Like Python, C++ supports the use of functions.

      6 |
    2. 7 |
    3. 8 |

      In C++, a function definition requires a name, a group of parameters, a return type, and a body.

      9 |
    4. 10 |
    5. 11 |

      Non-fruitful functions in C++ must contain the keyword void in its function definition.

      12 |
    6. 13 |
    7. 14 |

      You can pass variables by value as well as by reference in C++ functions. Passing by reference utilizes the use of pointers.

      15 |
    8. 16 |
    9. 17 |

      Pass by reference is useful when you require a function to return multiple variables.

      18 |
    10. 19 |
    11. 20 |

      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 ]).

      21 |
    12. 22 |

    23 | 24 | Reading Questions 25 | 26 |

    Drag each glossary term to its' corresponding definition.

    27 |

    Feedback shows incorrect matches.

    28 | argumentData passed to parameter.function Section of code that performs a procedure and usually is named meaningfully.overloadingSpecifying more than one definition for the same function name.
    29 | 30 |

    Drag each glossary term to its' corresponding definition.

    31 |

    Feedback shows incorrect matches.

    32 | 33 | parameterVariable in a function or method definition that accepts data passed from an argument.referenceValue that indicates an address in a computer's memory.voidindicates a function has no return value. 34 | constindicates a variable or value is unchanging. 35 | 36 | 37 | 38 |
    39 |
    40 |
    41 | 42 | -------------------------------------------------------------------------------- /theBook/whylearncpp.rst: -------------------------------------------------------------------------------- 1 | Why Learn another programming Language? 2 | ======================================= 3 | 4 | Python is a nice language for beginning programming for several reasons. 5 | First the syntax is sparse, and clear. Second, the underlying model of 6 | how objects and variables work is very consistent. Third, you can write 7 | powerful and interesting programs without a lot of work. However, Python 8 | is representative of one kind of language, called a dynamic language. 9 | You might think of Python as being fairly informal. There are other 10 | languages, like C++ and Java that are more formal. 11 | 12 | These languages have some advantages of their own. First, is speed: For 13 | very large programs C++ and Java are going to give you the best 14 | performance. Second is their maintainability. A lot of what makes Python 15 | easy to use is that you must remember certain things. For example if you 16 | set variable ``x`` to reference a turtle, and forget later that ``x`` is 17 | a turtle but try to invoke a string method on it, you will get an error. 18 | C++ protects you by forcing you to be upfront and formal about 19 | the kind of object each variable is going to refer to. 20 | 21 | In one sense Python is representative of a whole class of languages, 22 | sometimes referred to as “scripting languages.” Other languages in the 23 | same category as Python are Ruby and Perl. C++ is representative of 24 | what I will call industrial strength languages. Industrial strength 25 | languages are good for projects with several people working on the 26 | project where being formal and careful about what you do may impact lots 27 | of other people. Languages in this category include Java, C, C# and Ada. 28 | 29 | Programming languages will always change. As the field of computer 30 | science advances there will be new programming languages and you will 31 | need to learn them. It is important to learn several programming 32 | languages so that you know what to expect. There are certain features 33 | that most programming languages have in common; variables, loops, 34 | conditionals, functions. And there are some features that are unique. If 35 | you know what is common in languages that is a good place to start. 36 | 37 | Why Learn C++? Why not Java or Javascript? 38 | --------------------------------- 39 | 40 | - C++ influenced many programming languages such as Java, C# and other newer versions of C. 41 | 42 | - C++ introduced object-oriented programming. Among other things, C++ supports the four primary features of OOP: abstraction, inheritance, polymorphism and encapsulation. 43 | 44 | - C++ is industrial strength used for large systems by large groups of people. 45 | 46 | - C++ is better in interacting directly with the hardware. 47 | 48 | C++ is an enormous language and is very powerful. We will be using C++ throughout the semester to write interesting codes. 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Boilerplate list of files in a PreTeXt project for git to ignore 2 | # ensure this file is tracked 3 | !.gitignore 4 | 5 | # don't track unpublished builds or stage 6 | output 7 | 8 | # don't track assets generated from source 9 | generated-assets 10 | 11 | # don't track the executables.ptx file 12 | executables.ptx 13 | 14 | # don't track node packages 15 | node_modules 16 | 17 | # don't track error logs 18 | .error_schema.log 19 | cli.log 20 | **/cli.log 21 | logs 22 | 23 | # don't track OS related files (windows/macos/linux) 24 | .DS_Store 25 | .DS_Store? 26 | ._* 27 | .AppleDouble 28 | .LSOverride 29 | .Spotlight-V100 30 | .Trashes 31 | Icon 32 | .AppleDB 33 | .AppleDesktop 34 | Network Trash Folder 35 | Temporary Items 36 | .apdisk 37 | Thumbs.db 38 | Thumbs.db:encryptable 39 | ehthumbs.db 40 | ehthumbs_vista.db 41 | *.stackdump 42 | *.lnk 43 | *.cab 44 | *.msi 45 | *.msix 46 | *.msm 47 | *.msp 48 | [Dd]esktop.ini 49 | .directory 50 | .fuse_hidden* 51 | .Trash-* 52 | .nfs* 53 | .idea/* 54 | 55 | # Don't include VSCode generated files 56 | .vscode 57 | *.code-workspace 58 | 59 | # Don't inlucde SublimeText files 60 | # Cache files for Sublime Text 61 | *.tmlanguage.cache 62 | *.tmPreferences.cache 63 | *.stTheme.cache 64 | 65 | # Workspace files are user-specific 66 | *.sublime-workspace 67 | 68 | # Project files should be checked into the repository, unless a significant 69 | # proportion of contributors will probably not be using Sublime Text 70 | *.sublime-project 71 | 72 | # SFTP configuration file 73 | sftp-config.json 74 | sftp-config-alt*.json 75 | 76 | # Package control specific files 77 | Package Control.last-run 78 | Package Control.ca-list 79 | Package Control.ca-bundle 80 | Package Control.system-ca-bundle 81 | Package Control.cache/ 82 | Package Control.ca-certs/ 83 | Package Control.merged-ca-bundle 84 | Package Control.user-ca-bundle 85 | oscrypto-ca-bundle.crt 86 | bh_unicode_properties.cache 87 | 88 | # Sublime-github package stores a github token in this file 89 | # https://packagecontrol.io/packages/sublime-github 90 | GitHub.sublime-settings 91 | 92 | 93 | # Don't include Dropbox settings and caches 94 | .dropbox 95 | .dropbox.attr 96 | .dropbox.cache 97 | 98 | # Additionals based upon Pretextbook .gitignore 99 | user/* 100 | 101 | script/mjsre/node_modules/ 102 | script/mjsre/package-lock.json 103 | pretext/__pycache__/** 104 | 105 | # any file ending in ~ (backups, usually) 106 | *~ 107 | 108 | build_info 109 | **/_build 110 | **/rsbuild 111 | **/build 112 | build/* 113 | published 114 | 115 | # Codespaces set-up 116 | .devcontainer.json 117 | 118 | # ignore temp files 119 | temp-* 120 | 121 | # Ignore the following (from runestone .gitignore): 122 | 123 | *.pyc 124 | __pycache__/ 125 | 126 | sphinx-enki-info.txt 127 | sphinx_settings.json 128 | pavement.py 129 | 130 | # Don't track codechat config (will be generated automatically) 131 | codechat_config.yaml 132 | -------------------------------------------------------------------------------- /pretext/Turtles/differences.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Python's turtle vs C-Turtle 3 |

    C-Turtle varies from the Python turtle library primarily in syntax. Most of the methods 4 | are exactly the same between implementations, however there are a few notable differences between the two. 5 | Colors, for example, must be surrounded by curly brackets (e.g, ‘{' and ‘}') when referring to them by a 6 | name such as red, green, or blue. You can also ask for a random color by using the string random.

    7 | 8 | ct::Color red = {"red"}; 9 | ct::Color green = {"green"}; 10 | ct::Color blue = {"blue"}; 11 | ct::Color random = {"random"}; 12 | 13 | //This works due to the variable above... 14 | turtle.pencolor(red); 15 | 16 | //And so do these. 17 | turtle.pencolor({"green"}); 18 | turtle.pencolor({"random"}); 19 | 20 |

    Unlike in Python, the write method does not allow you to specify a font nor size. In contrast to Python, C++ finds it much more challenging to handle fonts because operating systems deal with them in a complex way. 21 | Furthermore, there is no world screen mode like 22 | there is in Python. Normally, this would allow you to specify the bounds of your canvas (e.g, specify minimum 23 | and maximum coordinates for your canvas).

    24 |

    Default shapes are also different and somewhat limited in comparison. Python offers six shapes by default, being arrow, circle, 25 | turtle, square, triangle, and classic. C-Turtle, on the other hand, offers four shapes by default: arrow, triangle, 26 | indented triangle, and square.

    27 |

    There are a few utility methods available in C-Turtle that are not available in Python, such as shift and middle. 28 | The former of the two, shift, simply adds to the X and Y coordinate position of the turtle. If your turtle is at coordinate 29 | 600x, 400y and shift is called with coordinate 50x and -50y, the turtle's final position would be 650x, 350y. The latter 30 | of the two, middle, returns the point exactly between two other points. See the examples below.

    31 | 32 | turtle.goTo(600, 400); 33 | turtle.shift(50, -50); 34 | //Turtle position is now 650x, 350y. 35 | 36 | 37 | ct::Point a = {400, 300}; 38 | ct::Point b = {450, 300}; 39 | 40 | //Should equal the point 425x, 300y. 41 | ct::Point middle = ct::middle(a, b); 42 | 43 |
    44 | 45 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/DealingWithIOFailures.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Dealing with I/O Failures 3 |

    File operations, such as opening and closing files, are often a source of runtime 4 | errors for various reasons. Well-written programs always should include error checking 5 | and Handling routines for possible problems dealing with files. Error checking 6 | and handling generally involves the programmer inserting statements in functions 7 | that perform I/O to check if any of the operations have failed. In C (the predecessor to C++), 8 | the system call to open a file returns a value after the function is called. 9 | A negative number means the operation failed for some reason, which the program can 10 | check to see if reading from a file is alright. In C++, a simple error checking mechanism 11 | is provided by the member function fail():

    12 |
    in_stream.fail();
    13 |

    This function returns true only if the previous stream operation for in_stream 14 | was not successful, such as if we tried to open a non-existent file. If a failure has 15 | occured, in_stream may be in a corrupted state and it is best not to attempt any more 16 | operations with it.

    17 |

    The following example code fragment safely quits the program entirely in case an I/O operation fails:

    18 |
    19 | 20 | 21 | #include <cstdlib< // for the fail member function 22 | #include <fstream< // for file I/O definitions 23 | #include <iostream< // for cout definition 24 | using namespace std; 25 | 26 | int main() { 27 | ifstream in_stream; 28 | // Try changing this to realFile.txt 29 | in_stream.open("realFile.txt"); 30 | if (in_stream.fail()) { 31 | cout << "Sorry, the file couldn't be opened!\n"; 32 | exit(1); // This exit value indicates an error happened (usual exit 33 | // value is 0) 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | 40 |
    41 |

    After opening the myFile.txt file, the if conditional checks to see if there was an error. If so, the program will output the apologetic error message and then exit. The exit(1) function from the library cstdlib enables the program to terminate at that point and have it return a 1 versus a 0, indicating an Error has occurred.

    42 |

    For more on Error Handling, see section 1.11.

    43 |
    44 | 45 | -------------------------------------------------------------------------------- /pretext/Functions/ArraysAsParameter.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Arrays as Parameters in Functions 3 |

    An array is a collection data type that is the ancestor of the Python list. 4 | We will discuss arrays in more detail in the next chapter. 5 | Functions can be used with array parameters to maintain a structured design. 6 | However, a formal parameter for an array is neither a call-by-value nor a call-by-reference, 7 | but a new type of parameter pass called an array parameter. 8 | In a function definition, an array parameter looks like a pass-by-value parameter 9 | because there is no ampersand symbol (&), but the variable name is instead followed 10 | by a set of square brackets ([ and ]).

    11 |

    The following example function returns the average hours worked over the array of 12 | integers (note that we need to also pass in the number of elements in that array 13 | because the array parameter list[] does not include that information):

    14 |
    double average( int list[], int length ) {
    15 |      // It is correct syntax to omit the array length on the array itself.
    16 |     double total = 0;
    17 |      //return type double which indicates that a decimal is being returned
    18 |     int count;
    19 |     for( count = 0; count < length; count++ ) {
    20 |         total += double(list[count]);
    21 |     };
    22 |     return (total / length);
    23 | }
    24 |

    Array parameters look like pass by value, but they are effectively similar to pass by reference parameters. When they execute, the functions with these parameters do not make private copies of the arrays. Instead, the reference is passed to reduce the impact on memory. Arrays can therefore always be permanently changed when passed as arguments to functions.

    25 |

    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:

    26 |
    void add_lists( int first[], int second[], int total[], int length ) {
    27 |     //return type void which indicates that nothing is returned
    28 |     int count;
    29 |     for( count = 0; count < length; count++ ) {
    30 |         total[count] = first[count] + second[count];
    31 | };}
    32 |

    Upon further examination, we can see that the first two arrays do not change values. To prevent ourselves from accidentally modifying any of these arrays, we can add the modifier const in the function head:

    33 |
    void add_lists( const int first[], const int second[], int total[], int length ) {
    34 |     //return type void which indicates that nothing is returned
    35 |     int count;
    36 |     for( count = 0; count < length; count++ ) {
    37 |         total[count] = first[count] + second[count];
    38 | };}
    39 |

    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.

    40 |
    41 | 42 | -------------------------------------------------------------------------------- /codechat_config.yaml: -------------------------------------------------------------------------------- 1 | # 2 | # (delete the above line to manage this file manually) 3 | # 4 | ############################################################# 5 | # 6 | # This file allows the use of the CodeChat previewer for PreTeXt. 7 | # Generally, there is no need to modify this file. 8 | # It will be automatically generated by PreTeXt with the latest 9 | # updates unless you remove the first comment line above. 10 | # 11 | ############################################################ 12 | # 13 | # .. Copyright (C) 2012-2023 Bryan A. Jones. 14 | # 15 | # This file is part of the CodeChat System. 16 | # 17 | # The CodeChat System is free software: you can redistribute it and/or 18 | # modify it under the terms of the GNU General Public License as 19 | # published by the Free Software Foundation, either version 3 of the 20 | # License, or (at your option) any later version. 21 | # 22 | # The CodeChat System is distributed in the hope that it will be 23 | # useful, but WITHOUT ANY WARRANTY; without even the implied warranty 24 | # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 25 | # General Public License for more details. 26 | # 27 | # You should have received a copy of the GNU General Public License 28 | # along with the CodeChat System. If not, see 29 | # . 30 | # 31 | # ************************************************ 32 | # |docname| - Configuration for a CodeChat project 33 | # ************************************************ 34 | # This file defines the configuration for a CodeChat project. It contains a working `PreTeXt `_ configuration. 35 | # 36 | # ``source_path``: optional; defaults to ``.`` (the current directory). A path to the root of the source tree. Relative paths are rooted in the directory containing this configuration file. 37 | source_path: source 38 | 39 | # ``output_path``: required. A path to the root of the HTML output produced by this renderer. Relative paths are rooted in the directory containing this configuration file. 40 | output_path: output/web 41 | 42 | # ``args``: required string or sequence of strings. This provides the arguments to invoke the renderer. These strings may optionally contain the following replacement values: 43 | # 44 | # - ``{project_path}``: an absolute path to the directory containing this file. 45 | # - ``{source_path}``: the ``source_path`` above, but as an absolute path. 46 | # - ``{output_path}``: the ``output_path`` above, but as an absolute path. 47 | # - ``{sys_executable}``: the value of the running Python's `sys.executable `_. 48 | # - ``{xml_id}``: The value of the the first ``xml:id`` attribute in the currently open file. 49 | args: "{sys_executable} -m pretext build web --xmlid {xml_id}" 50 | 51 | # ``html_ext``: optional; defaults to ``.html``. The extension used by this renderer when generating HTML files. 52 | #html_ext: .html 53 | 54 | # ``project_type``: optional; defaults to ``general``. Define the project type, which enables special processing based on the type. Valid values are ``general`` (no special processing), ``Doxygen``, and ``PreTeXt``. 55 | project_type: PreTeXt 56 | -------------------------------------------------------------------------------- /_sources/Control_Structures/while_loop.rst: -------------------------------------------------------------------------------- 1 | While Loops 2 | ============ 3 | 4 | As we noted earlier, algorithms require two important control 5 | structures: iteration and selection. Both of these are supported by 6 | Python in various forms. The programmer can choose the statement that is 7 | most useful for the given circumstance. 8 | 9 | For repeating a block of code, C++ provides a standard ``while`` and ``for`` constructs. 10 | The ``while`` construct repeats a body of code as long as a condition is true. For example, 11 | 12 | :: 13 | 14 | int counter = 1; 15 | while (counter <= 5) { /*Use of an interactive method until the 16 | the loop ends */ 17 | cout << "Hello, world" << endl; 18 | counter = counter + 1; 19 | } 20 | 21 | Console output: 22 | Hello, world 23 | Hello, world 24 | Hello, world 25 | Hello, world 26 | Hello, world 27 | 28 | 29 | prints out the phrase “Hello, world” five times. The condition on the 30 | ``while`` statement is evaluated at the start of each repetition. If the 31 | condition is ``true``, the body of the statement will execute. 32 | 33 | The ``while`` statement is a very general purpose iterative structure 34 | that we will use in a number of different algorithms. In many cases, a 35 | compound condition will control the iteration. A fragment such as 36 | 37 | :: 38 | 39 | while ((counter <= 10) && (!done)) { 40 | ... 41 | 42 | 43 | would cause the body of the statement to be executed only in the case 44 | where both parts of the condition are satisfied due to the and operator (``&&``). The value of the 45 | variable ``counter`` would need to be less than or equal to 10 and the 46 | value of the variable ``done`` would need to be ``false`` (``not false`` 47 | is ``true``) so that ``true and true`` results in ``true``. 48 | 49 | Here are some of the logical operators that are useful for true-false boolean statements in C++. 50 | 51 | :: 52 | 53 | and - && 54 | 55 | or - || 56 | 57 | not equal to - != 58 | 59 | not - ! 60 | 61 | greater than - > 62 | 63 | less than - < 64 | 65 | greater than 66 | or equal to - >= 67 | 68 | less than 69 | or equal to - <= 70 | 71 | 72 | These are the same as we saw in earlier chapters. 73 | 74 | 75 | 76 | :: 77 | 78 | #include 79 | using namespace std; 80 | 81 | int main(){ 82 | int counter = 0; 83 | while (counter <= 1) { 84 | cout << "Hello, world!" << endl; 85 | } 86 | }; 87 | 88 | 89 | .. mchoice:: mc_whileloop 90 | :answer_a: "0" is written 1 time. 91 | :answer_b: "Hello world!" is written 1 time. 92 | :answer_c: "Hello world!" is written infinitely many times. 93 | :answer_d: None of the above. 94 | :correct: c 95 | :feedback_a: Take a look at the cout line. 96 | :feedback_b: Take a closer look at the while loop 97 | :feedback_c: Right! because counter is never greater than one, thus making the while loop infinite. 98 | :feedback_d: Not quite, take another look. 99 | 100 | Using the code above please select the answer that should appear. 101 | -------------------------------------------------------------------------------- /pretext/IntroCpp/glossary.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Glossary 3 | 4 | 5 | 6 | <title_reference>cin</title_reference> 7 | 8 |

    cin stands for console input. It is the standard input statement in C++.

    9 | 10 |
    11 | 12 | comment 13 | 14 |

    A comment is a programmer-readable explanation in the source code of a computer program (// single line comment, /**/ Multiline comment).

    15 | 16 |
    17 | 18 | compiler 19 | 20 |

    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.

    21 | 22 |
    23 | 24 | <title_reference>cout</title_reference> 25 | 26 |

    cout stands for console output. It is the standard output statement in C++.

    27 | 28 |
    29 | 30 | dynamically typed 31 | 32 |

    A dynamically typed programming languages is one in which variables need not necessarily be defined before they are used, and can change during execution.

    33 | 34 |
    35 | 36 | header 37 | 38 |

    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.

    39 | 40 |
    41 | 42 | #include 43 | 44 |

    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.

    45 | 46 |
    47 | 48 | interpreter 49 | 50 |

    An interpreter directly executes statements in a scripting language without requiring them to have been compiled into machine language.

    51 | 52 |
    53 | 54 | machine code 55 | 56 |

    machine code is a computer program written in instructions that can be directly executed by a computer's CPU.

    57 | 58 |
    59 | 60 | statically typed 61 | 62 |

    A statically typed programming languages is one in which variables must be defined before they are used and cannot change during execution.

    63 | 64 |
    65 | 66 |
    67 |
    68 | 69 | -------------------------------------------------------------------------------- /pavement.py: -------------------------------------------------------------------------------- 1 | import paver 2 | from paver.easy import * 3 | import paver.setuputils 4 | 5 | paver.setuputils.install_distutils_tasks() 6 | from os import environ, getcwd 7 | import os.path 8 | import sys 9 | from socket import gethostname 10 | import pkg_resources 11 | from runestone import get_master_url 12 | 13 | sys.path.append(getcwd()) 14 | sys.path.append("../modules") 15 | 16 | updateProgressTables = True 17 | try: 18 | from runestone.server.chapternames import populateChapterInfob 19 | except ImportError: 20 | updateProgressTables = False 21 | 22 | 23 | ######## CHANGE THIS ########## 24 | project_name = "cpp4python" 25 | ############################### 26 | 27 | master_url = None 28 | doctrees = "./build/{}/doctrees".format(project_name) 29 | dynamic_pages = True 30 | 31 | if master_url is None: 32 | master_url = get_master_url() 33 | 34 | master_app = "runestone" 35 | serving_dir = "./build/" + project_name 36 | dest = "./published" 37 | 38 | options( 39 | sphinx=Bunch( 40 | docroot=".", 41 | ), 42 | build=Bunch( 43 | builddir="./build/" + project_name, 44 | sourcedir="./_sources/", 45 | outdir="./build/" + project_name, 46 | confdir=".", 47 | project_name=project_name, 48 | doctrees=doctrees, 49 | template_args={ 50 | "course_id": project_name, 51 | "course_title": "C++\\ for\\ Python\\ Programmers", 52 | "login_required": "false", 53 | "appname": master_app, 54 | "loglevel": 10, 55 | "course_url": master_url, 56 | "use_services": "true", 57 | "python3": "true", 58 | "dynamic_pages": dynamic_pages, 59 | "dburl": "postgresql://bmiller@localhost/runestone", 60 | "basecourse": "thinkcspy", 61 | "downloads_enabled": "false", 62 | "default_ac_lang": "python", 63 | "enable_chatcodes": "false", 64 | "allow_pairs": "false", 65 | }, 66 | ), 67 | ) 68 | 69 | if project_name == "": 70 | print("Please edit pavement.py and give your project a name") 71 | exit() 72 | 73 | version = pkg_resources.require("runestone")[0].version 74 | options.build.template_args["runestone_version"] = version 75 | 76 | if ( 77 | "DBHOST" in environ 78 | and "DBPASS" in environ 79 | and "DBUSER" in environ 80 | and "DBNAME" in environ 81 | ): 82 | options.build.template_args[ 83 | "dburl" 84 | ] = "postgresql://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}".format(**environ) 85 | 86 | from runestone import build 87 | 88 | # build is called implicitly by the paver driver. 89 | 90 | template_args = { 91 | "course_id": project_name, 92 | "course_title": "C++\\ for\\ Python\\ Programmers", 93 | "login_required": "false", 94 | "appname": master_app, 95 | "loglevel": 10, 96 | "course_url": master_url, 97 | "use_services": "true", 98 | "python3": "true", 99 | "dynamic_pages": dynamic_pages, 100 | "dburl": "postgresql://bmiller@localhost/runestone", 101 | "basecourse": "thinkcspy", 102 | "downloads_enabled": "false", 103 | "default_ac_lang": "python", 104 | "enable_chatcodes": "false", 105 | "allow_pairs": "false", 106 | } -------------------------------------------------------------------------------- /_sources/IntroCpp/glossary.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce and Brad Miller 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Glossary 6 | -------- 7 | 8 | .. glossary:: 9 | 10 | `cin` 11 | `cin` stands for "console input". It is the standard input statement in C++. 12 | 13 | comment 14 | A comment is a programmer-readable explanation in the source code of a computer program (``//`` single line comment, ``/**/`` Multiline comment). 15 | 16 | compiler 17 | 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. 18 | 19 | `cout` 20 | `cout` stands for "console output". It is the standard output statement in C++. 21 | 22 | dynamically typed 23 | A dynamically typed programming languages is one in which variables need not necessarily be defined before they are used, and can change during execution. 24 | 25 | header 26 | 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. 27 | 28 | #include 29 | 30 | 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. 31 | 32 | interpreter 33 | An interpreter directly executes statements in a scripting language without requiring them to have been compiled into machine language. 34 | 35 | machine code 36 | machine code is a computer program written in instructions that can be directly executed by a computer's CPU. 37 | 38 | statically typed 39 | A statically typed programming languages is one in which variables must be defined before they are used and cannot change during execution. 40 | 41 | 42 | Matching 43 | -------- 44 | .. dragndrop:: matching_intro 45 | :feedback: Feedback shows incorrect matches. 46 | :match_1: cin|||Standard input statement in C++. 47 | :match_2: comment|||a readable explanation in the source code of a computer program. 48 | :match_3: compiler|||Creates an executeable program by transforming code written in a high-level programming language into a low-level programming language. 49 | :match_4: cout|||Standard output statement in C++. 50 | :match_5: dynamically typed|||Programing language, in which variables need not necessarily be defined before they are used, and can change during execution. 51 | :match_6: header|||library files that contain a variety of useful definitions. They are imported into any C++ program by using the #include statement. 52 | :match_7: #include|||Tells the preprocessor to treat the contents of a specified file as if they appear in the source program at the point where the directive appears. 53 | :match_8: interpreter|||directly executes statements in a scripting language without requiring them to have been compiled into machine language 54 | :match_9: machine code||| a computer program written in instructions that can be directly executed by a computer's CPU. 55 | :match_10: statically typed|||Programming language, in which variables must be defined before they are used and cannot change during execution. 56 | 57 | Drag each glossary term to its' corresponding definition. -------------------------------------------------------------------------------- /pretext/Input_and_Output/PuttingItAllTogether.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Putting it all Together 3 |

    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.

    4 |
    5 | 6 | 7 | #include <cstdlib> // for the exit function 8 | #include <fstream> // for I/O member functions 9 | #include <iostream> // for cout 10 | using namespace std; // To avoid writing std:: before standard library components 11 | 12 | int main() { 13 | // Declare variables for file names and file streams 14 | char in_file_name[16], // Arrays to store filenames (max 15 chars + null terminator) 15 | out_file_name[16]; 16 | ifstream in_stream; // Input file stream object 17 | ofstream out_stream;// Output file stream object 18 | 19 | // Prompt the user for input and output file names 20 | cout << "This program will sum three numbers taken from an input\n" 21 | << "file and write the sum to an output file." << endl; 22 | cout << "Enter the input file name (maximum of 15 characters):\n"; 23 | cin >> in_file_name; 24 | cout << "\nEnter the output file name (maximum of 15 characters):\n"; 25 | cin >> out_file_name; 26 | cout << endl; 27 | 28 | // Condensed input and output file opening and checking. 29 | in_stream.open(in_file_name); 30 | out_stream.open(out_file_name); 31 | 32 | if (in_stream.fail() || out_stream.fail()) { 33 | cout << "Input or output file opening failed.\n"; 34 | exit(1); // Terminate the program with an error code 35 | } 36 | 37 | // Declare variables to store numbers and their sum 38 | double firstn, secondn, thirdn, sum = 0.0; 39 | 40 | // Read the first three numbers from the input file 41 | cout << "Reading numbers from the file " << in_file_name << endl; 42 | in_stream >> firstn >> secondn >> thirdn; 43 | sum = firstn + secondn + thirdn; 44 | 45 | // The following set of lines will write to the screen 46 | cout << "The sum of the first 3 numbers from " << in_file_name << " is " 47 | << sum << endl; 48 | 49 | cout << "Placing the sum into the file " << out_file_name << endl; 50 | 51 | // The following set of lines will write to the output file 52 | out_stream << "The sum of the first 3 numbers from " << in_file_name 53 | << " is " << sum << endl; 54 | 55 | // Close the file streams 56 | in_stream.close(); 57 | out_stream.close(); 58 | 59 | cout << "End of Program." << endl; 60 | 61 | return 0; 62 | 63 | 64 | }
    65 |
    66 | 67 | -------------------------------------------------------------------------------- /_sources/index.rst: -------------------------------------------------------------------------------- 1 | .. C++ for Python Programmers documentation master file, originally created by 2 | sphinx-quickstart on Thu Oct 27 08:17:45 2011. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. meta:: 7 | :description: An interactive book designed to help learners transition from Python to C++. 8 | :keywords: C++, cpp, Python, computer science 9 | 10 | .. toc_version: 2 11 | 12 | =========================== 13 | C++ for Python Programmers 14 | =========================== 15 | 16 | By Jan Pearce, Berea College and Brad Miller, Runestone 17 | 18 | .. raw:: html 19 | 20 | 23 | 24 | .. toctree:: 25 | :numbered: 26 | :maxdepth: 3 27 | 28 | IntroCpp/toctree.rst 29 | AtomicData/toctree.rst 30 | Control_Structures/toctree.rst 31 | Functions/toctree.rst 32 | CollectionData/toctree.rst 33 | Input_and_Output/toctree.rst 34 | Exception_Handling/toctree.rst 35 | Turtles/toctree.rst 36 | 37 | Reporting Typos or Other Problems 38 | ::::::::::::::::::::::::::::::::: 39 | 40 | Thank you for your help in improving this text. If you find a typo or other problem, you can visit the `Github issue tracker `_ giving as much information as needed to understand the problem. If you include the URL of the page where the problem occurred, this is especially helpful. Alternatively, you can contact the author `Jan Pearce `_ via email. 41 | 42 | 43 | Acknowledgements 44 | :::::::::::::::: 45 | https://www.berea.edu/csc/faculty-and-staff/dr-jan-pearce/ 46 | Many thanks to Runestone for creating a very strong framework for open source computing books. 47 | Many thanks also to Berea College's Labor Program for making it possible for students to 48 | undergraduate students to receive funding to contribute. 49 | 50 | Some sections of this book were originally written by Dr. Brad Miller as 51 | *Java for Python Programmers*. These were translated to the C++ language 52 | by Dr. Jan Pearce and a team of excellent students from Berea College. 53 | Other sections were originally written as course web pages by Dr. Jan Pearce. 54 | 55 | We would like to extend a special note of gratitude to 56 | `Jesse Walker-Schadler `_ 57 | who had the vision to create the `CTurtle library `_ 58 | which makes graphing in C++ particularly easy for Python programmers because it used the 59 | Python Turtle library syntax, and for his excellent work in porting it to Runestone. 60 | 61 | Index and Search 62 | :::::::::::::::: 63 | 64 | * :ref:`genindex` 65 | * :ref:`search` 66 | 67 | 68 | .. raw:: html 69 | 70 |
    71 | 72 | Creative Commons License 74 |
    C++ for Python Programmers by 76 | 77 | Janice L. Pearce and Bradley N. Miller is licensed under a 78 | 79 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
    80 | -------------------------------------------------------------------------------- /pretext/AtomicData/CharactersData.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Character Data 3 |

    In Python strings can be created with single or double quotes. 4 | In C++ single quotes are used for the character (char) data type, 5 | and double quotes are used for the string data type.

    6 |

    Consider the following code.

    7 | 8 | 9 | 10 | 11 | # Shows direct comparison of both Strings & Characters in Python 12 | def main(): 13 | 14 | strvar = "b" 15 | charvar = 'b' 16 | 17 | print('b' == charvar) 18 | print("b" == strvar) 19 | print('a' == "a") 20 | 21 | main() 22 | 23 | 24 | 25 | 26 | 27 | 28 | #include <iostream> 29 | #include <string> 30 | using namespace std; 31 | 32 | // Demonstrates how chars and strings can not be 33 | // directly compared. 34 | int main(){ 35 | 36 | string strvar = "b"; 37 | char charvar = 'b'; 38 | 39 | cout << ('b' == charvar) << endl; 40 | cout << ("b" == strvar) << endl; 41 | //cout << ('a' == "a") << endl; // will error! 42 | 43 | return 0; 44 | } 45 | 46 | 47 | 48 |

    Try the following question.

    49 | 50 | 51 | 52 | 53 |

    Q-3: If I want to create a string in C++, what set of symbols may be used?

    54 | 55 |
    56 | 57 | 58 | 59 | 60 |

    ' '

    61 |
    62 | 63 |

    No, single quotes are only used for single characters.

    64 |
    65 |
    66 | 67 | 68 | 69 |

    " "

    70 |
    71 | 72 |

    Good job reading!

    73 |
    74 |
    75 | 76 | 77 | 78 |

    ' ' or " " may be used

    79 |
    80 | 81 |

    No. Only one set of symbols may be used.

    82 |
    83 |
    84 | 85 | 86 | 87 |

    It depends upon the implementation.

    88 |
    89 | 90 |

    No. The implementation is consistent.

    91 |
    92 |
    93 | 94 | 95 | 96 |

    none of the above

    97 |
    98 | 99 |

    One of the above is indeed correct.

    100 |
    101 |
    102 |
    103 | 104 |
    105 |
    106 | 107 | -------------------------------------------------------------------------------- /pretext/Exception_Handling/Summary.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Summary & Reading Questions 3 |

      4 |
    1. 5 |

      There are two types of errors that occur while writing programs: syntax errors and logic errors

      6 |
    2. 7 |
    3. 8 |

      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.

      9 |
    4. 10 |
    5. 11 |

      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.

      12 |
    6. 13 |
    7. 14 |

      logic errors can be caught by using try and catch which can help pinpoint what is causing the error and avoid confusion about the problem.

      15 |
    8. 16 |

    17 | 18 | Reading Questions 19 | 20 | 21 | 22 |

    Click on the syntax error.

    23 |

    Remember, syntax errors occur more for people learning a new language.

    24 | 25 | int age; 26 | cout << "age"; 27 | cin >> age; 28 | if (age > 18) { 29 | 30 | cout << "You can vote in all countries with an 18 year old age for voting!";} 31 | else { 32 | cout << You cannot vote in all countries with an 18 year old age for voting.; 33 | 34 | } 35 |
    36 | 37 |

    Click on the logic error.

    38 |

    If we want the code to say when we are old enough to vote, what cases should it say when can and cannot?

    39 | 40 | int age; 41 | cout << "age"; 42 | cin >> age; 43 | if (age < 18) { 44 | 45 | cout << "You can vote in all countries with an 18 year old age for voting!";} 46 | else { 47 | cout << "You cannot vote in all countries with an 18 year old age for voting."; 48 | 49 | } 50 |
    51 | 52 | 53 |

    Match the words with their corresponding definition.

    54 |

    Feedback shows incorrect matches.

    55 | 56 | exceptionResponse to an unusual circumstance while a program is running. 57 | logic error Error in which the program/code functions, but performs incorrectly. 58 | runtime errorError occurs when a program encounters an issue during its execution. 59 | syntax errorError in the structure of a statement or expression of code.
    60 |
    61 | 62 |
    63 | 64 | -------------------------------------------------------------------------------- /pretext/AtomicData/CharacterData.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Character Data 3 |

    In Python strings can be created with single or double quotes. 4 | In C++ single quotes are used for the character (char) data type, 5 | and double quotes are used for the string data type.

    6 |

    Consider the following code.

    7 | 8 | 9 | 10 | 11 | # Shows direct comparison of both Strings & Characters in Python 12 | def main(): 13 | 14 | strvar = "b" 15 | charvar = 'b' 16 | 17 | print('b' == charvar) 18 | print("b" == strvar) 19 | print('a' == "a") 20 | 21 | main() 22 | 23 | 24 | 25 | 26 | 27 | 28 | #include <iostream> 29 | #include <string> 30 | using namespace std; 31 | 32 | // Demonstrates how chars and strings can not be 33 | // directly compared. 34 | int main(){ 35 | 36 | string strvar = "b"; 37 | char charvar = 'b'; 38 | 39 | cout << ('b' == charvar) << endl; 40 | cout << ("b" == strvar) << endl; 41 | //cout << ('a' == "a") << endl; // will error! 42 | 43 | return 0; 44 | } 45 | 46 | 47 | 48 |

    Try the following question.

    49 | 50 | Reading Question 51 | 52 | 53 | 54 |

    If I want to create a string in C++, what set of symbols may be used?

    55 | 56 |
    57 | 58 | 59 | 60 | 61 |

    ' '

    62 |
    63 | 64 |

    No, single quotes are only used for single characters.

    65 |
    66 |
    67 | 68 | 69 | 70 |

    " "

    71 |
    72 | 73 |

    Good job reading!

    74 |
    75 |
    76 | 77 | 78 | 79 |

    ' ' or " " may be used

    80 |
    81 | 82 |

    No. Only one set of symbols may be used.

    83 |
    84 |
    85 | 86 | 87 | 88 |

    It depends upon the implementation.

    89 |
    90 | 91 |

    No. The implementation is consistent.

    92 |
    93 |
    94 | 95 | 96 | 97 |

    none of the above

    98 |
    99 | 100 |

    One of the above is indeed correct.

    101 |
    102 |
    103 |
    104 | 105 |
    106 |
    107 |
    -------------------------------------------------------------------------------- /_sources/IntroCpp/whylearncpp.rst: -------------------------------------------------------------------------------- 1 | Why Learn Another Programming Language? 2 | ======================================= 3 | 4 | Python is a great language for beginning programming for several reasons. 5 | First, the syntax is both sparse and clear. Second, the underlying model of 6 | how objects and variables work is very consistent. Third, you can write 7 | powerful and interesting programs without a lot of work. However, Python 8 | is representative of one kind of language, called a dynamic language. 9 | One might think of Python as being fairly informal. Other 10 | languages, like C, C++, and Java are more formal. 11 | 12 | These other more formal languages have some advantages of their own. 13 | First, is speed: For very large programs C and C++ are likely to give you the best 14 | performance. Second, is their maintainability. Python 15 | requires you to remember certain things. For example if you 16 | set variable ``t`` to reference a turtle, and forget later that ``t`` is 17 | a turtle but try to invoke a string method on it, you will get an error. 18 | C++ protects you from this kind of error by forcing you to be upfront and formal about 19 | the type of object each variable is going to refer to. 20 | 21 | In one sense Python is representative of a whole class of interpreted languages, 22 | sometimes referred to as “scripting languages.” Other scripting languages 23 | include Ruby and Perl. C++ is representative of 24 | what one might call industrial strength languages. Industrial strength 25 | languages are good for projects with several or many people working on the 26 | project where being formal and careful about what you do may impact lots 27 | of other people. Languages in this category include C, C#, C++, Ada, and Java. 28 | 29 | The good news is that learning a second programming language is much easier than learning 30 | your first programming language because you will be able to draw upon your existing knowledge. 31 | Programming languages are likely to regularly change as time passes. 32 | As the field of computer science advances there are likely to be new programming 33 | languages that you will want or need to learn. There are certain features 34 | that most programming languages have in common such as variables, loops, 35 | conditionals, and functions. And there are other language features that are unique. If 36 | you know what is common in most languages, then in learning a new language, you need only 37 | to focus on what is different from the languages you already know. 38 | 39 | Why Learn C++? Why not Java or Javascript? 40 | ------------------------------------------ 41 | 42 | - C++ is an enormous language which is very powerful because it is a high-level language that offers low-level features, 43 | but one only needs to learn a small part of the language to write effective code. 44 | 45 | - C++ influenced many programming languages such as C#, Java, and other newer versions of C, so by learning C++, 46 | learning these other languages becomes much easier. 47 | 48 | - C++ is an industrial strength programming language and is very often used today for large systems by large groups of people. 49 | 50 | - C++ is particularly good at interacting directly with computer hardware, making execution very fast. 51 | 52 | - C++ was the first widely used object-oriented programming (OOP) language, 53 | supporting the four primary features of OOP: 54 | abstraction, inheritance, polymorphism, and encapsulation. 55 | 56 | - C++ allows the programmer to create and use a data type called a pointer explicitly, 57 | which can increase control over both memory and performance under certain circumstances. 58 | 59 | - Because C++ is fast, it is currently the language of choice for virtual reality. 60 | 61 | - Also, because C++ is fast, it is the language of choice of many 2D and 3D game engines. 62 | 63 | - For all of the above reasons, even though C++ is an older language, 64 | it is still one of the top listed in job advertisements. 65 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/FileOperations.ptx: -------------------------------------------------------------------------------- 1 |
    2 | File Operations 3 |

    Having created a stream with the declaration above, we can connect it to a file (i.e. open the file) using the member function open(filename). For example, the following statement will allow the C++ program to open the file called myFile.txt, assuming a file named that exists in the current directory, and connect in_stream to the beginning of the file:

    4 |
    in_stream.open("myFile.txt");
    5 |

    Once connected, the program can read from that file. Pictorially, this is what happens:

    6 | 7 |
    image
    8 |

    the <ofstream> class also has an open(filename) member function, but it is defined differently. Consider the following statement:

    9 |
    out_stream.open("anotherFile.txt");
    10 |

    Pictorally, we get a stream of data flowing out of the program:

    11 | 12 |
    image
    13 |

    Because out_stream is an object of type <ofstream>, connecting it to the file named anotherFile.txt will create that file if it does not exist. If the file anotherFile.txt already exists, it will be wiped and replaced with whatever is fed into the output stream.

    14 |

    To disconnect the ifstream in_stream from whatever file it opened, we use its close() member function:

    15 |
    in_stream.close();
    16 |

    To close the file for out_stream, we use its close() function, which also adds an end-of-file marker to indicate where the end of the file is:

    17 |
    out_stream.close();
    18 |

    Answer the question below concerning the use of the fstream library:

    19 | 20 | Reading Question 21 | 22 | 23 | 24 | 25 |

    Say you wanted to add some text to a file that already has important information on it. 26 | Would it be a good idea to first use ofstream to open the file?

    27 | 28 |
    29 | 30 | 31 | 32 | 33 |

    Yes, ofstream is required to edit the file.

    34 |
    35 | 36 |

    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.

    37 |
    38 |
    39 | 40 | 41 | 42 |

    Yes, using ifstream will wipe the file clean without using ofstream first.

    43 |
    44 | 45 |

    Wrong! ifstream is only used to read files, therefore it will never edit the contents of one.

    46 |
    47 |
    48 | 49 | 50 | 51 |

    No, using ofstream on a file that already has information on it will clear the entire file.

    52 |
    53 | 54 |

    Correct!

    55 |
    56 |
    57 | 58 | 59 | 60 |

    No, ofstream is exclusively used for reading files.

    61 |
    62 | 63 |

    Wrong! ifstream is used to read files instead.

    64 |
    65 |
    66 |
    67 | 68 |
    69 |
    70 |
    71 | 72 | -------------------------------------------------------------------------------- /pretext/Control_Structures/for_loop.ptx: -------------------------------------------------------------------------------- 1 |
    2 | For Loops 3 |

    Even though the while type of construct is very useful in a wide variety of 4 | situations, another iterative structure, the for statement, can be 5 | used to iterate across a range of values easily. 6 | A for statement allows us to write a loop that is executed a specific number of times.

    7 | 8 | 9 | 10 | #include <iostream> 11 | using namespace std; 12 | 13 | int main() { 14 | for (int i = 0; i < 10; i++){ 15 | cout << i << "hello world" << endl; 16 | } 17 | } 18 | 19 | 20 |

    In the example above, the hello world statement is executed 10 times.

    21 |

    A common use of the for construct is to implement certain repetition 22 | over a range of values.

    23 | 24 | 25 | 26 | #include <iostream> 27 | using namespace std; 28 | 29 | // squares the numebers in range 5 30 | // ex. 0*0, 1*1, 2*2 ... 31 | int main() { 32 | for (int i=0; i<5; i++) { 33 | cout << i*i << " "; 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | 40 |

    The code will use cout five times. The value of the variable i will 41 | start at 0 and go through the full sequence of values 0,1,2,3,4. This 42 | value is then squared and printed.

    43 | 44 | Check yourself 45 |
    #include <iostream>
     46 | using namespace std;
     47 | 
     48 | int main() {
     49 | 
     50 |     for (int counter=0; counter<4; counter++) {
     51 |         cout << counter * 2 << " ";
     52 |     }
     53 | 
     54 |     return 0;
     55 | }
    56 | 57 | Reading Question 58 | 59 | 60 | 61 |

    Using the code above please select the answer that should appear?

    62 | 63 |
    64 | 65 | 66 | 67 | 68 |

    0 2 4 6

    69 |
    70 | 71 |

    Good Job!

    72 |
    73 |
    74 | 75 | 76 | 77 |

    0 0 0 0

    78 |
    79 | 80 |

    Not quite, take another look at the operation happening in the cout line

    81 |
    82 |
    83 | 84 | 85 | 86 |

    Runtime error

    87 |
    88 | 89 |

    Not quite, take another look at the for loop

    90 |
    91 |
    92 | 93 | 94 | 95 |

    0 1 2 3

    96 |
    97 | 98 |

    Not quite, take another look at the operation happening in the cout line

    99 |
    100 |
    101 | 102 | 103 | 104 |

    all of the above

    105 |
    106 | 107 |

    108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |

    116 | 117 | -------------------------------------------------------------------------------- /pretext/Turtles/glossary.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Glossary 3 | 4 | 5 | 6 | back 7 | 8 |

    Moves the turtle backwards a specified number of units.

    9 | 10 |
    11 | 12 | beginfill 13 | 14 |

    Begins to fill the shape indicated by the path the turtle takes after calling it.

    15 | 16 |
    17 | 18 | delay 19 | 20 |

    Adds a delay at the end of the frame.

    21 | 22 |
    23 | 24 | endfill 25 | 26 |

    Finishes filling the shape the turtle has outlined since calling beginfill.

    27 | 28 |
    29 | 30 | fillcolor 31 | 32 |

    Tells the turtle what collor to fill the object it is drawing.

    33 | 34 |
    35 | 36 | forward 37 | 38 |

    Tells the turtle to go forward a certin number of units.

    39 | 40 |
    41 | 42 | goto 43 | 44 |

    Moves the turtle to a specified coordinate on the canvas.

    45 | 46 |
    47 | 48 | left 49 | 50 |

    Turns the turtle to the left a specified number of units.

    51 | 52 |
    53 | 54 | pencolor 55 | 56 |

    Tells the turtle what color it will draw the outline as.

    57 | 58 |
    59 | 60 | penup 61 | 62 |

    Tells the turtle to pick up its paintbrush.

    63 | 64 |
    65 | 66 | pendown 67 | 68 |

    Tells the turtle to put its paintbrush down.

    69 | 70 |
    71 | 72 | right 73 | 74 |

    Turns the turtle to the right a specified number of units.

    75 | 76 |
    77 | 78 | speed 79 | 80 |

    Tells the turtle how fast to draw.

    81 | 82 |
    83 | 84 | undo queue 85 | 86 |

    A queue of actions the turtle has previously taken.

    87 | 88 |
    89 | 90 | width 91 | 92 |

    Tells the turtle how wide its paintbrush should be.

    93 | 94 |
    95 | 96 | write 97 | 98 |

    Tells the turtle to write text at its current position.

    99 | 100 |
    101 | 102 |
    103 |
    104 | 105 | -------------------------------------------------------------------------------- /pretext/AtomicData/CheckYourself.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Check Yourself 3 | 4 | 5 | 6 | 7 |

    Q-20: If I want to use the char type in C++, what set of symbols must be used?

    8 | 9 |
    10 | 11 | 12 | 13 | 14 |

    ' '

    15 |
    16 | 17 |

    Right!

    18 |
    19 |
    20 | 21 | 22 | 23 |

    " "

    24 |
    25 | 26 |

    No. Double quotes are only used for strings.

    27 |
    28 |
    29 | 30 | 31 | 32 |

    ' ' or " " may be used

    33 |
    34 | 35 |

    No. Only one set of symbols may be used.

    36 |
    37 |
    38 | 39 | 40 | 41 |

    It depends upon the implementation.

    42 |
    43 | 44 |

    No. The implementation is consistent.

    45 |
    46 |
    47 | 48 | 49 | 50 |

    none of the above

    51 |
    52 | 53 |

    One of the above is indeed correct.

    54 |
    55 |
    56 |
    57 | 58 |
    59 | 60 | 61 | 62 |

    Q-21: A/an ___ is used to store a memory address in C++?

    Right!

    Be more specific!

    That’s Python, not C++!

    Incorrect. Please try again

    63 | 64 | 65 | 66 |

    Q-22: How may one reference a variable’s memory address in C++?

    67 | 68 |
    69 | 70 | 71 | 72 | 73 |

    using ``&``

    74 |
    75 | 76 |

    Right! ``&`` is the "address-of" operator, used to reference an address.

    77 |
    78 |
    79 | 80 | 81 | 82 |

    using ``*``

    83 |
    84 | 85 |

    No. ``int *p;`` defines a pointer to an integer, and ``*p`` would dereference that pointer, i.e. retrieve the data that p points to.

    86 |
    87 |
    88 | 89 | 90 | 91 |

    using ``id``

    92 |
    93 | 94 |

    No. This is used in Python.

    95 |
    96 |
    97 | 98 | 99 | 100 |

    It depends upon the implementation.

    101 |
    102 | 103 |

    No. Try again.

    104 |
    105 |
    106 | 107 | 108 | 109 |

    none of the above

    110 |
    111 | 112 |

    One of the above is indeed correct.

    113 |
    114 |
    115 |
    116 | 117 |
    118 |
    119 | -------------------------------------------------------------------------------- /pretext/Control_Structures/while_loop.ptx: -------------------------------------------------------------------------------- 1 |
    2 | While Loops 3 |

    As we noted earlier, algorithms require two important control 4 | structures: iteration and selection. Both of these are supported by 5 | Python in various forms. The programmer can choose the statement that is 6 | most useful for the given circumstance.

    7 |

    For repeating a block of code, C++ provides a standard while and for constructs. 8 | The while construct repeats a body of code as long as a condition is true. For example,

    9 |
    int counter = 1;
     10 | while (counter <= 5) {          /*Use of an interactive method until the
     11 |                                  the loop ends   */
     12 |     cout << "Hello, world" << endl;
     13 |     counter = counter + 1;
     14 | }
     15 | 
     16 | Console output:
     17 | Hello, world
     18 | Hello, world
     19 | Hello, world
     20 | Hello, world
     21 | Hello, world
    22 |

    prints out the phrase Hello, world five times. The condition on the 23 | while statement is evaluated at the start of each repetition. If the 24 | condition is true, the body of the statement will execute.

    25 |

    The while statement is a very general purpose iterative structure 26 | that we will use in a number of different algorithms. In many cases, a 27 | compound condition will control the iteration. A fragment such as

    28 |
    while ((counter <= 10) && (!done)) {
     29 | ...
    30 |

    would cause the body of the statement to be executed only in the case 31 | where both parts of the condition are satisfied due to the and operator (&&). The value of the 32 | variable counter would need to be less than or equal to 10 and the 33 | value of the variable done would need to be false (not false 34 | is true) so that true and true results in true.

    35 |

    Here are some of the logical operators that are useful for true-false boolean statements in C++.

    36 |
    and          - &&
     37 | 
     38 | or           - ||
     39 | 
     40 | not equal to - !=
     41 | 
     42 | not          - !
     43 | 
     44 | greater than - >
     45 | 
     46 | less than    - <
     47 | 
     48 | greater than
     49 | or equal to  - >=
     50 | 
     51 | less than
     52 | or equal to  - <=
    53 |

    These are the same as we saw in earlier chapters.

    54 |
    #include <iostream>
     55 | using namespace std;
     56 | 
     57 | int main(){
     58 |     int counter = 0;
     59 |     while (counter <= 1) {
     60 |         cout << "Hello, world!" << endl;
     61 |     }
     62 | };
    63 | 64 | Reading Question 65 | 66 | 67 | 68 | 69 | 70 | 71 |

    Using the code above please select the answer that should appear.

    72 | 73 |
    74 | 75 | 76 | 77 | 78 |

    "0" is written 1 time.

    79 |
    80 | 81 |

    Take a look at the cout line.

    82 |
    83 |
    84 | 85 | 86 | 87 |

    "Hello world!" is written 1 time.

    88 |
    89 | 90 |

    Take a closer look at the while loop

    91 |
    92 |
    93 | 94 | 95 | 96 |

    "Hello world!" is written infinitely many times.

    97 |
    98 | 99 |

    Right! because counter is never greater than one, thus making the while loop infinite.

    100 |
    101 |
    102 | 103 | 104 | 105 |

    None of the above.

    106 |
    107 | 108 |

    Not quite, take another look.

    109 |
    110 |
    111 |
    112 | 113 |
    114 |
    115 |
    116 | 117 | -------------------------------------------------------------------------------- /_sources/Turtles/pattern_application.rst: -------------------------------------------------------------------------------- 1 | Practical Application - Tessellation 2 | ==================================== 3 | 4 | Art takes a variety of forms, ranging from abstract to realistic, 5 | and consisting of an impossibly wide variety of materials. 6 | Ancient Sumerians would dye and dry small pieces of clay to create mosaics. 7 | These mosaics were often composed of shapes and patterns that would overlap 8 | without any gaps in between them. This art form is known today as tessellation, 9 | which can be observed in any modern building that is composed of bricks, 10 | or any floor covered in ceramic tiles. Mosaics are defined by their interlocking shapes, 11 | however, what these shapes are made of‒ or, the medium‒ varies depending on the artist. 12 | 13 | The common mediums for this art form have changed over time, 14 | ranging from pieces of clay to pieces of wood. More recently, 15 | digital mediums have been used as an effective alternative to physical materials. 16 | Turtles are one of many such digital mediums, and are often used to 17 | create images rich in repetitive features. Your task will be to create 18 | a mosaic-like tessellating image using turtles. 19 | 20 | Consider the following examples. 21 | 22 | .. activecode:: cturtle_practical_example_cpp 23 | :language: cpp 24 | 25 | #include 26 | namespace ct = cturtle; 27 | 28 | int main() { 29 | const int SQUARE_SIZE = 35; 30 | 31 | ct::TurtleScreen scr; 32 | scr.tracer(0);//disable animation 33 | ct::Turtle turtle(scr); 34 | turtle.speed(ct::TS_FASTEST); 35 | turtle.penup(); 36 | 37 | for(int i = 0; i < 8; i++){ 38 | turtle.goTo(-scr.window_width()/2,-scr.window_height()/2+ (i*SQUARE_SIZE)+SQUARE_SIZE); 39 | 40 | bool is_blue = i % 2 == 0;//even (true) or odd (false) row? 41 | 42 | for(int j = 0; j < 8; j++){ 43 | ct::Color color; 44 | 45 | if(is_blue){ 46 | color = {"blue"}; 47 | }else{ 48 | color = {"orange"}; 49 | } 50 | 51 | turtle.begin_fill(); 52 | turtle.fillcolor(color); 53 | 54 | for(int i = 0; i < 4; i++){ 55 | turtle.forward(SQUARE_SIZE); 56 | turtle.right(90); 57 | } 58 | 59 | turtle.end_fill(); 60 | 61 | turtle.forward(SQUARE_SIZE); 62 | is_blue = !is_blue;//flip-flop between true and false 63 | } 64 | } 65 | 66 | scr.bye(); 67 | return 0; 68 | } 69 | 70 | .. activecode:: cturtle_practical_example_Python 71 | :language: Python 72 | 73 | import turtle 74 | 75 | SQUARE_SIZE = 35 76 | 77 | wn = turtle.Screen() 78 | wn.tracer(0); 79 | square = turtle.Turtle() 80 | square.speed(10) 81 | square.pu() 82 | square.goto(-turtle.window_width()/2,turtle.window_height()/2); 83 | square.pd() 84 | 85 | a = 0 86 | b = 0 87 | for i in range(8): 88 | if(b == 0): 89 | a=1 90 | else: 91 | a=0 92 | for j in range(8): 93 | square.penup() 94 | square.goto(-turtle.window_width() / 2 + j * SQUARE_SIZE, (-turtle.window_height() / 2) + i * SQUARE_SIZE + SQUARE_SIZE) 95 | square.pendown() 96 | if(a==0): 97 | square.fillcolor('orange') 98 | a=1 99 | else: 100 | square.fillcolor('blue') 101 | a=0 102 | square.begin_fill() 103 | for k in range(4): 104 | square.forward(SQUARE_SIZE) 105 | square.right(90) 106 | square.end_fill() 107 | if(b==0): 108 | b=1 109 | else: 110 | b=0 111 | wn.tracer(1) 112 | 113 | 114 | You must create a similar image with the following criteria: 115 | 116 | - There must not be four edges in your chosen shape, but 3 or 5+ is fine. 117 | - There must be no more than two colors for the shapes in the image. 118 | 119 | .. activecode:: cturtle_practical_prompt 120 | :language: cpp 121 | 122 | #include 123 | namespace ct = cturtle; 124 | 125 | int main() { 126 | ct::TurtleScreen scr; 127 | scr.tracer(0);//disable animation 128 | ct::Turtle turtle(scr); 129 | 130 | //Your code here 131 | 132 | scr.bye(); 133 | return 0; 134 | } 135 | 136 | -------------------------------------------------------------------------------- /pretext/Turtles/pattern_application.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Practical Application - Tessellation 3 |

    Art takes a variety of forms, ranging from abstract to realistic, 4 | and consisting of an impossibly wide variety of materials. 5 | Ancient Sumerians would dye and dry small pieces of clay to create mosaics. 6 | These mosaics were often composed of shapes and patterns that would overlap 7 | without any gaps in between them. This art form is known today as tessellation, 8 | which can be observed in any modern building that is composed of bricks, 9 | or any floor covered in ceramic tiles. Mosaics are defined by their interlocking shapes, 10 | however, what these shapes are made of‒ or, the medium‒ varies depending on the artist.

    11 |

    The common mediums for this art form have changed over time, 12 | ranging from pieces of clay to pieces of wood. More recently, 13 | digital mediums have been used as an effective alternative to physical materials. 14 | Turtles are one of many such digital mediums, and are often used to 15 | create images rich in repetitive features. Your task will be to create 16 | a mosaic-like tessellating image using turtles.

    17 |

    Consider the following examples.

    18 | 19 | 20 | 21 | #include <CTurtle.hpp> 22 | namespace ct = cturtle; 23 | 24 | int main() { 25 | const int SQUARE_SIZE = 35; 26 | 27 | ct::TurtleScreen scr; 28 | scr.tracer(0);//disable animation 29 | ct::Turtle turtle(scr); 30 | turtle.speed(ct::TS_FASTEST); 31 | turtle.penup(); 32 | 33 | for(int i = 0; i < 8; i++){ 34 | turtle.goTo(-scr.window_width()/2,-scr.window_height()/2+ (i*SQUARE_SIZE)+SQUARE_SIZE); 35 | 36 | bool is_blue = i % 2 == 0;//even (true) or odd (false) row? 37 | 38 | for(int j = 0; j < 8; j++){ 39 | ct::Color color; 40 | 41 | if(is_blue){ 42 | color = {"blue"}; 43 | }else{ 44 | color = {"orange"}; 45 | } 46 | 47 | turtle.begin_fill(); 48 | turtle.fillcolor(color); 49 | 50 | for(int i = 0; i < 4; i++){ 51 | turtle.forward(SQUARE_SIZE); 52 | turtle.right(90); 53 | } 54 | 55 | turtle.end_fill(); 56 | 57 | turtle.forward(SQUARE_SIZE); 58 | is_blue = !is_blue;//flip-flop between true and false 59 | } 60 | } 61 | 62 | scr.bye(); 63 | return 0; 64 | } 65 | 66 | 67 | 68 | 69 | 70 | import turtle 71 | 72 | SQUARE_SIZE = 35 73 | 74 | wn = turtle.Screen() 75 | wn.tracer(0); 76 | square = turtle.Turtle() 77 | square.speed(10) 78 | square.pu() 79 | square.goto(-turtle.window_width()/2,turtle.window_height()/2); 80 | square.pd() 81 | 82 | a = 0 83 | b = 0 84 | for i in range(8): 85 | if(b == 0): 86 | a=1 87 | else: 88 | a=0 89 | for j in range(8): 90 | square.penup() 91 | square.goto(-turtle.window_width() / 2 + j * SQUARE_SIZE, (-turtle.window_height() / 2) + i * SQUARE_SIZE + SQUARE_SIZE) 92 | square.pendown() 93 | if(a==0): 94 | square.fillcolor('orange') 95 | a=1 96 | else: 97 | square.fillcolor('blue') 98 | a=0 99 | square.begin_fill() 100 | for k in range(4): 101 | square.forward(SQUARE_SIZE) 102 | square.right(90) 103 | square.end_fill() 104 | if(b==0): 105 | b=1 106 | else: 107 | b=0 108 | wn.tracer(1) 109 | 110 | 111 |

    You must create a similar image with the following criteria:

    112 |

      113 |
    • 114 |

      There must not be four edges in your chosen shape, but 3 or 5+ is fine.

      115 |
    • 116 |
    • 117 |

      There must be no more than two colors for the shapes in the image.

      118 |
    • 119 |

    120 | 121 | 122 | 123 | #include <CTurtle.hpp> 124 | namespace ct = cturtle; 125 | 126 | int main() { 127 | ct::TurtleScreen scr; 128 | scr.tracer(0);//disable animation 129 | ct::Turtle turtle(scr); 130 | 131 | //Your code here 132 | 133 | scr.bye(); 134 | return 0; 135 | } 136 | 137 | 138 |
    139 | 140 | -------------------------------------------------------------------------------- /_sources/Turtles/introduction.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | C++ is designed with the principal that speed is more important than safety and error-checking. 5 | This differs from languages like Python, which is considerably more restrictive in regards to 6 | aspects such as memory allocations and resource management. C++ is translated to "machine language" 7 | when it is compiled, which is a step skipped by Python. Python skips this step in favor of immediate 8 | interpretation of the code itself. 9 | 10 | This difference is what allows C++ to be as fast as it is, which also makes it particularly good 11 | for graphically-intensive applications. Graphical applications heavily leverage memory management 12 | to display every pixel you see on your screen. Python does not allow for the creation of arrays like in 13 | C++, which are just "chunks" of memory of a fixed size. Furthermore, running directly on the hardware 14 | allows C++ to communicate better with other components of your computer, such as your graphics processing unit, or "GPU". 15 | This is one of many reasons C++ is considered an industry standard for high-performance graphics applications, such as 16 | video games or software used for visual effects in movies. 17 | 18 | What are Turtles? 19 | ======================= 20 | Turtle graphics are a popular and simple way for introducing programming to beginners. 21 | It was part of the original Logo programming language developed by 22 | Wally Feurzeig, Seymour Papert, and Cynthia Solomon in 1967. 23 | 24 | Imagine turtles as being a digital marker used for drawing various shapes, images, and designs. 25 | Drawing with Turtles can be as basic as a simple triangle and as complex as a highly detailed fractal image. 26 | Nearly all commands used when drawing with Turtles are as simple as telling your Turtle to move forward, backward, 27 | left, and right in as few or many steps as desired. 28 | 29 | The :code:`turtle` library is commonly used in Python. This chapter will cover a close analog for turtle graphics between 30 | Python and C++, the :code:`C-Turtle` library. 31 | 32 | Turtles in C++ 33 | ======================================= 34 | 35 | Python is particularly well-suited for educational purposes due to its 36 | wide array of built in tools and good documentation. These things are particularly 37 | lacking in regards to C++, as many of the built-in tools require complicated syntax 38 | and deep understanding of the language itself. One of these tools is the :code:`turtle` library, 39 | which is very well suited for educational purposes because it offers live, interactive, 40 | and visual representations of your code. 41 | 42 | Visual representations afford students an opportunity to observe a facet of computer science 43 | from an alternative point of view: rather than waiting anxiously for the print statement 44 | to come around after your program churns, you get a visual representation of the concept itself. 45 | This is particularly useful for abstract concepts such as recursion and iteration. 46 | 47 | For C++, a library called :code:`C-Turtle` is used to provide an equivalent of Python's :code:`turtle`. 48 | It acts as a close replacement to provide easy to use graphics to C++, while maintaining 49 | the objects and commands you might be used to in Python. It was developed by Jesse Walker-Schadler 50 | at Berea College during the summer of 2019, and can be found on GitHub here: https://github.com/walkerje/C-Turtle 51 | 52 | Below is a comparison of the two versions, C++ and Python, which do 53 | the same thing. Try running both and comparing how the code looks between the two versions. 54 | 55 | .. activecode:: cturtle_1 56 | :language: cpp 57 | 58 | #include 59 | namespace ct = cturtle; 60 | 61 | int main() { 62 | ct::TurtleScreen scr; 63 | ct::Turtle turtle(scr); 64 | turtle.speed(ct::TS_SLOWEST); 65 | turtle.fillcolor({"purple"}); 66 | turtle.begin_fill(); 67 | for (int i = 0; i < 4; i++) { 68 | turtle.forward(50); 69 | turtle.right(90); 70 | } 71 | turtle.end_fill(); 72 | scr.bye(); 73 | return 0; 74 | } 75 | 76 | .. activecode:: cturtle_python_1 77 | :language: python 78 | 79 | import turtle 80 | 81 | turt = turtle.Turtle() 82 | turt.fillcolor("purple") 83 | turt.speed("slowest") 84 | 85 | turt.begin_fill() 86 | for i in range(4): 87 | turt.forward(50) 88 | turt.right(90) 89 | turt.end_fill() 90 | 91 | .. mchoice:: cturtle_question_1 92 | :answer_a: Students receive instant feedback and gratification for their work. 93 | :answer_b: Students will pay less attention to how their code works, and more attention to its end result. 94 | :answer_c: Students get more acquainted with RGB values common in web development. 95 | :answer_d: Students will be more comfortable working with concepts they are used to, such as Turtles. 96 | :correct: a, d 97 | :feedback_a: Correct! 98 | :feedback_b: Incorrect, because equal thought must be put into the usage of Turtles as well as the outcome. 99 | :feedback_c: Incorrect, because RGB values are not the focus or reason behind using Turtles. 100 | :feedback_d: Correct! 101 | 102 | How might students benefit from having a visual representation such as C-Turtle? Check all that apply. 103 | -------------------------------------------------------------------------------- /pretext/IntroCpp/whylearncpp.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Why Learn Another Programming Language? 3 |

    Python is a great language for beginning programming for several reasons. 4 | First, the syntax is both sparse and clear. Second, the underlying model of 5 | how objects and variables work is very consistent. Third, you can write 6 | powerful and interesting programs without a lot of work. However, Python 7 | is representative of one kind of language, called a dynamic language. 8 | One might think of Python as being fairly informal. Other 9 | languages, like C, C++, and Java are more formal.

    10 |

    These other more formal languages have some advantages of their own. 11 | First, is speed: For very large programs C and C++ are likely to give you the best 12 | performance. Second, is their maintainability. Python 13 | requires you to remember certain things. For example if you 14 | set variable t to reference a turtle, and forget later that t is 15 | a turtle but try to invoke a string method on it, you will get an error. 16 | C++ protects you from this kind of error by forcing you to be upfront and formal about 17 | the type of object each variable is going to refer to.

    18 |

    In one sense Python is representative of a whole class of interpreted languages, 19 | sometimes referred to as scripting languages. Other scripting languages 20 | include Ruby and Perl. C++ is representative of 21 | what one might call industrial strength languages. Industrial strength 22 | languages are good for projects with several or many people working on the 23 | project where being formal and careful about what you do may impact lots 24 | of other people. Languages in this category include C, C#, C++, Ada, and Java.

    25 |

    The good news is that learning a second programming language is much easier than learning 26 | your first programming language because you will be able to draw upon your existing knowledge. 27 | Programming languages are likely to regularly change as time passes. 28 | As the field of computer science advances there are likely to be new programming 29 | languages that you will want or need to learn. There are certain features 30 | that most programming languages have in common such as variables, loops, 31 | conditionals, and functions. And there are other language features that are unique. If 32 | you know what is common in most languages, then in learning a new language, you need only 33 | to focus on what is different from the languages you already know.

    34 | 35 | Why Learn C++? Why not Java or Javascript? 36 |
    37 |

      38 |
    • 39 |

      C++ is an enormous language which is very powerful because it is a high-level language that offers low-level features, 40 | but one only needs to learn a small part of the language to write effective code.

      41 |
    • 42 |
    • 43 |

      C++ influenced many programming languages such as C#, Java, and other newer versions of C, so by learning C++, 44 | learning these other languages becomes much easier.

      45 |
    • 46 |
    • 47 |

      C++ is an industrial strength programming language and is very often used today for large systems by large groups of people.

      48 |
    • 49 |
    • 50 |

      C++ is particularly good at interacting directly with computer hardware, making execution very fast.

      51 |
    • 52 |
    • 53 |

      C++ was the first widely used object-oriented programming (OOP) language, 54 | supporting the four primary features of OOP: 55 | abstraction, inheritance, polymorphism, and encapsulation.

      56 |
    • 57 |
    • 58 |

      C++ allows the programmer to create and use a data type called a pointer explicitly, 59 | which can increase control over both memory and performance under certain circumstances.

      60 |
    • 61 |
    • 62 |

      Because C++ is fast, it is currently the language of choice for virtual reality.

      63 |
    • 64 |
    • 65 |

      Also, because C++ is fast, it is the language of choice of many 2D and 3D game engines.

      66 |
    • 67 |
    • 68 |

      For all of the above reasons, even though C++ is an older language, 69 | it is still one of the top listed in job advertisements.

      70 |
    • 71 |

    72 |
    73 |
    74 |
    75 | 76 | -------------------------------------------------------------------------------- /_sources/Turtles/advanced_features.rst: -------------------------------------------------------------------------------- 1 | Advanced Features 2 | ================= 3 | 4 | Turtles are a large tool, and thus have a lot of options dictating how they function. 5 | Some features and functionality are more complicated than others, relating to the inner workings 6 | of turtles themselves. A few of these include the :code:`tracer` and :code:`undo` methods, and also screen modes. 7 | 8 | Screen modes dictate the direction of angle measurements. This means that, depending on which mode a :code:`TurtleScreen` 9 | object is in, positive angles could represent clockwise rotations or counterclockwise rotations. The :code:`mode` method 10 | for :code:`TurtleScreen` allows you to set which mode a screen is in. 11 | 12 | =========== ================ ================ 13 | Mode Default Rotation Positive Angles 14 | =========== ================ ================ 15 | SM_STANDARD East Counterclockwise 16 | SM_LOGO North Clockwise 17 | =========== ================ ================ 18 | 19 | Regarding angles, Turtles can use both *degrees* and *radians* for their rotations. You can choose between the two using the 20 | :code:`radians` and :code:`degrees` methods for the Turtle object. By default, all angles are measured in *degrees*. This option 21 | only effects methods regarding rotation, such as :code:`left` and :code:`right`. 22 | 23 | .. code-block:: cpp 24 | 25 | turtle.degrees(); 26 | turtle.right(90);//90-degree turn to the right 27 | turtle.radians(); 28 | turtle.left(1.5708f);//Equivalent rotation in radians to the left. 29 | 30 | The :code:`tracer(N)` method is used to control how many times the Turtle is actually 31 | drawn on the screen. This method belongs to the :code:`TurtleScreen` object, and effects 32 | all turtles that are on the screen. The :code:`N` in the method represents the input, 33 | only allowing the :code:`TurtleScreen` to display one frame out every :code:`N`. 34 | 35 | .. code-block:: cpp 36 | 37 | screen.tracer(12); 38 | //Show one out of every 12 frames of animation. 39 | 40 | This can be combined with the :code:`speed` method available to turtles to achieve **very** quickly 41 | drawn images. The maximum speed a Turtle can have, :code:`TS_FASTEST`, completely disables animation 42 | for Turtles between movements and rotations. This allows the :code:`tracer` setting to directly relate 43 | to the total number of actions the turtle makes. The actions the turtle takes happen regardless 44 | of whether or not they are actually shown on the screen. 45 | 46 | .. code-block:: cpp 47 | 48 | screen.tracer(3); //Show one out of every 3 frames of animation. 49 | turtle.speed(ct::TS_FASTEST); //Disables Turtle animation 50 | 51 | turtle.forward(50);//This is not shown on-screen... 52 | turtle.right(90);//Neither is this... 53 | turtle.forward(50);//But this action is, because it is third out of three. 54 | 55 | A frame of animation is added for almost every action a turtle takes, regardless of whether or not 56 | the turtle is moving or adding something to the screen. This includes methods like 57 | :code:`begin_fill` and :code:`end_fill`, which don't do anything visually but do 58 | tell the turtle to start or stop tracking its own movements. 59 | 60 | Consider the following example and related questions. 61 | 62 | .. code-block:: cpp 63 | 64 | #include 65 | namespace ct = cturtle; 66 | 67 | int main(){ 68 | ct::TurtleScreen screen; 69 | ct::Turtle turtle(screen); 70 | 71 | turtle.speed(ct::TS_FASTEST); 72 | screen.tracer(6); 73 | 74 | for(int i = 0; i < 3; i++){ 75 | turtle.right(60); 76 | turtle.forward(50); 77 | } 78 | 79 | screen.bye(); 80 | 81 | return 0; 82 | } 83 | 84 | .. mchoice:: cturtle_advanced_mchoice_1 85 | :answer_a: 3 86 | :answer_b: 6 87 | :answer_c: 1 88 | :answer_d: 12 89 | :correct: c 90 | :feedback_a: Incorrect! Consider how many actions the turtle takes in the for loop. 91 | :feedback_b: Incorrect! Consider the tracer setting for the screen. 92 | :feedback_c: Correct! 93 | :feedback_d: Incorrect! Consider how many actions the turtle takes in the for loop. 94 | 95 | How many frames of animation does the above code create? 96 | 97 | Similarly to tracer settings, every action a turtle takes is also added to the *undo queue*. This allows it to keep track 98 | 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. 99 | This is modifiable through the :code:`setundobuffer` method that belongs to turtles. Every action is added, even if 100 | the action doesn't change anything visually. This feature is comparable to the "undo" tool available in most text editors. 101 | Turtles can "undo" their progress with the :code:`undo` method. 102 | 103 | .. mchoice:: cturtle_advanced_mchoice_2 104 | :answer_a: 3 105 | :answer_b: 6 106 | :answer_c: 1 107 | :answer_d: 12 108 | :correct: b 109 | :feedback_a: Incorrect! Consider how many actions the turtle takes in the for loop. 110 | :feedback_b: Correct! 111 | :feedback_c: Incorrect! Consider how many actions the turtle takes in the for loop. 112 | :feedback_d: Incorrect! Consider how many actions the turtle takes in the for loop. 113 | 114 | How many actions will be in the turtle's undo queue for the code above? 115 | -------------------------------------------------------------------------------- /pretext/Input_and_Output/Summary.ptx: -------------------------------------------------------------------------------- 1 |
    2 | Summary & Reading Questions 3 |

      4 |
    1. 5 |

      File handling in C++ uses stream similar to cout and cin in <iosteam> library but is <fstream> for file stream.

      6 |
    2. 7 |
    3. 8 |

      ifstream in_stream creates an input stream object, in_stream, that can be used to input text from a file to C++.

      9 |
    4. 10 |
    5. 11 |

      ofstream out_stream creates an output stream object,out_steam, that can be used to write text from C++ to a file.

      12 |
    6. 13 |
    7. 14 |

      End-of-File or .eof() is a method for the instance variables of fstream, input and output stream objects, and can be used to carry out a task until a file has ended or do some task after a file has ended.

      15 |
    8. 16 |

    17 | 18 | Reading Questions 19 | 20 | 21 | 22 | 23 |

    Which of the following are libraries for C++ input and output? (Choose all that are true.)

    24 | 25 |
    26 | 27 | 28 | 29 | 30 |

    fstream

    31 |
    32 | 33 |

    Yes, fstream is library for handling file input and output.

    34 |
    35 |
    36 | 37 | 38 | 39 |

    ifstream

    40 |
    41 | 42 |

    No, ifstream is an object type for handling input.

    43 |
    44 |
    45 | 46 | 47 | 48 |

    ofstream

    49 |
    50 | 51 |

    No, ofstream is an object type for handling output.

    52 |
    53 |
    54 | 55 | 56 | 57 |

    iostream

    58 |
    59 | 60 |

    Yes, iostream is a library for handling console input and output.

    61 |
    62 |
    63 |
    64 | 65 |
    66 | 67 | 68 |

    Drag the corresponding library to what you would use it for.

    69 |
    70 |

    Which library is used for which task?

    71 | fstreamI want to write to a fileiostreamI want to write to the console 72 |
    73 | 74 | 75 | 76 |

    Fill in the blank with the value of inputn when the following code runs. 77 |

    78 |
    #include <fstream>
     79 |             #include <cstdlib>
     80 |             #include <iostream>
     81 |             using namespace std;
     82 |             
     83 |             main(){
     84 |               ifstream in_stream;
     85 |               ofstream out_stream;
     86 |               int inputn;
     87 |             
     88 |               out_stream.open("anotherFile.txt");
     89 |               out_stream << 25;
     90 |               out_stream << 15 << endl;
     91 |               out_stream << 101 << endl;
     92 |             
     93 |               in_stream.open("anotherFile.txt");
     94 |               in_stream >> inputn;
     95 |               cout << inputn;
     96 |               in_stream >> inputn;
     97 |             }
    98 |
    99 | 100 | 101 | 102 |

    That is the correct answer! Good job!

    103 |

    No. Hint: inputn is changed twice.

    104 |

    No. Hint: inputn is changed twice.

    105 |

    No. Hint: note that there is no space between the first 25 and 15!

    106 |
    107 |
    108 |
    109 | 110 | 111 |

    Match the words to thier corresponding definition.

    112 |

    Feedback shows incorrect matches.

    113 | 114 | streamAn abstraction that allows you to send or receive an unknown number of bytes in input or output. 115 | member functionA function that's associated with a certain type of object.c-stringAn array of characters that ends with a terminating null character.End-Of-FileA flag that lets programs know when to stop. 116 | 117 |
    118 |
    119 |
    120 | 121 | -------------------------------------------------------------------------------- /_sources/Turtles/geometry_shapes_stamps.rst: -------------------------------------------------------------------------------- 1 | Geometry, Shapes, and Stamps 2 | ============================ 3 | 4 | Every basic shape in :code:`C-Turtle` is a set of coordinates. Within the :code:`C-Turtle` library 5 | we have the choice of a select few shapes that we can me our Turtles inhabit. 6 | To change the appearance of your Turtle, you can use :code:`shape` to set your Turtle to 7 | one of four default shapes, or a custom shape. :code:`C-Turtle` features four default shapes, :code:`triangle`, 8 | :code:`indented_triangle`, :code:`square`, and :code:`arrow`. 9 | 10 | The following code example shows how to set the shape of a turtle by giving it the name of a shape. 11 | 12 | .. code-block:: cpp 13 | 14 | turtle.shape("square"); 15 | 16 | Given that all primitive shapes are defined as a collection of points, all of the default shapes are also defined this way. 17 | Polygons, for custom and default shapes, must have their points defined in counter-clockwise order to appear correctly. 18 | This is due to the mathematics behind filling arbitrary shapes, and is a limitation almost all computer graphics need to 19 | abide by. Consider the order of their points in the following table, and how they could be considered "counter-clockwise". 20 | They are in order from top to bottom, and one edge exists between the first last points for each of these shapes. Please note 21 | that positive Y coordinates are *lower* on the screen, while negative Y coordinates are *higher* on the screen. Coordinates at 22 | the origin-- that is, coordinate 0x, 0y-- is at the "point" or "tip" of the turtle. This is why most of the default shapes 23 | have their first coordinate there. 24 | 25 | ======== ===================== ========== ======== 26 | triangle indented_triangle square arrow 27 | ======== ===================== ========== ======== 28 | (0, 0) (0, 0) (-5, -5) (0, 0) 29 | (-5, 5) (-5, 10) (-5, 5) (-5, 5) 30 | (5, 5) (0, 8) (5, 5) (-3, 5) 31 | . (5, 10) (5, 10) (-3, 10) 32 | . . . (3, 10) 33 | . . . (3, 5) 34 | . . . (5, 5) 35 | ======== ===================== ========== ======== 36 | 37 | Using the default :code:`indented_triangle` shape as an example, Figure 1 shows the nature of the counter-clockwise order. 38 | 39 | .. figure:: cc_polygon.png 40 | :align: center 41 | :alt: All points must be oriented, in order and in a leftwards direction, relative to the center of the entire shape. 42 | 43 | Figure 1: Indented Triangle Definition 44 | 45 | The example code below illustrates how to create your own shape. We use the :code:`Polygon` class to represent our shape. 46 | For this example, we take the :code:`triangle` default shape and make every Y coordinate negative to make it appear upside-down. 47 | 48 | .. code-block:: cpp 49 | 50 | ct::Polygon upside_down_triangle = { 51 | {0, 0}, //First point 52 | {-5, -5}, //Second point 53 | {5, -5} //and so on. 54 | }; 55 | 56 | The following code is a full example for setting your turtle to a custom shape. Feel free to mess around with 57 | the coordinates of the polygon, you might surprise yourself with what shape you end up with! 58 | 59 | .. activecode:: cturtle_geometry_ac_1 60 | :language: cpp 61 | 62 | #include 63 | namespace ct = cturtle; 64 | 65 | int main(){ 66 | ct::TurtleScreen screen; 67 | screen.tracer(1, 1000); 68 | ct::Turtle turtle(screen); 69 | 70 | ct::Polygon upside_down_triangle = { 71 | {0, 0}, //First point 72 | {-5, -5}, //Second point 73 | {5, -5} //and so on. 74 | }; 75 | 76 | turtle.shape(upside_down_triangle); 77 | turtle.forward(50); 78 | 79 | screen.bye(); 80 | return 0; 81 | } 82 | 83 | Stamps provide a way to make several copies of the shape of the turtle across the screen without having to trace each 84 | shape individually with the turtle. This can be used for a variety of visual effects, however it is often used as a 85 | time-saving utility. Stamps can be placed with the :code:`stamp` method of Turtle objects, which returns an integer 86 | that acts as the **ID** of the stamp that has been placed. The :code:`clearstamp` method of the Turtle object can 87 | be used to delete a single stamp from the screen, while the :code:`clearstamps` method is used to delete multiple 88 | stamps at once. 89 | 90 | The following code is a full example showing how to combine custom shapes with stamp placement. 91 | 92 | .. activecode:: cturtle_geometry_ac_2 93 | :language: cpp 94 | 95 | #include 96 | namespace ct = cturtle; 97 | 98 | int main(){ 99 | ct::TurtleScreen screen; 100 | screen.tracer(1, 1000); 101 | ct::Turtle turtle(screen); 102 | 103 | ct::Polygon upside_down_triangle = { 104 | {0, 0}, //First point 105 | {-5, -5}, //Second point 106 | {5, -5} //and so on. 107 | }; 108 | 109 | turtle.shape(upside_down_triangle); 110 | 111 | //Draw a square where each edge is 50 units long. 112 | for(int i = 0; i < 4; i++){ 113 | //Stamp at the corner of the square. 114 | int corner_stamp = turtle.stamp(); 115 | 116 | turtle.forward(25); 117 | turtle.stamp(); //Stamp half-way across the edge of the square. 118 | turtle.forward(25); 119 | 120 | turtle.right(90); 121 | //Clear the corner stamp. 122 | turtle.clearstamp(corner_stamp); 123 | } 124 | 125 | turtle.clearstamps(); 126 | 127 | screen.bye(); 128 | return 0; 129 | } -------------------------------------------------------------------------------- /theBook/conditionals.rst: -------------------------------------------------------------------------------- 1 | Conditionals 2 | ============ 3 | 4 | Conditional statements in Python and C++ are very similar. In Python we 5 | have three patterns: 6 | 7 | Simple if 8 | --------- 9 | 10 | :: 11 | 12 | if condition: 13 | statement1 14 | statement2 15 | ... 16 | 17 | In C++ this same pattern is simply written as: 18 | 19 | :: 20 | 21 | if (condition) { 22 | statement1 23 | statement2 24 | ... 25 | } 26 | 27 | Once again you can see that in C++ the curly braces define a block 28 | rather than indentation. In C++ the parenthesis around the condition 29 | are required because if is technically a function that evaluates to True 30 | or False. 31 | 32 | if else 33 | ------- 34 | 35 | :: 36 | 37 | if condition: 38 | statement1 39 | statement2 40 | ... 41 | else: 42 | statement1 43 | statement2 44 | ... 45 | 46 | In C++ this is written as: 47 | 48 | :: 49 | 50 | if (condition) { 51 | statement1 52 | statement2 53 | ... 54 | } else { 55 | statement1 56 | statement2 57 | ... 58 | } 59 | 60 | elif 61 | ---- 62 | 63 | C++ does not have an elif pattern like Python. In C++ you can get the 64 | functionality of an elif statement by nesting if and else. Here is a 65 | simple example in both Python and C++. 66 | 67 | .. activecode :: pyelif 68 | :language: python 69 | 70 | grade = int(input('enter a grade')) 71 | if grade < 60: 72 | print('F') 73 | elif grade < 70: 74 | print('D') 75 | elif grade < 80: 76 | print('C') 77 | elif grade < 90: 78 | print('B') 79 | else: 80 | print('A') 81 | 82 | In C++ we have a couple of ways to write this 83 | 84 | .. activecode:: C++elif 85 | :language: C++ 86 | :sourcefile: ElseIf.cpp 87 | 88 | #include 89 | using namespace std; 90 | 91 | int main() { 92 | int grade = 85; 93 | 94 | if (grade < 60) { 95 | cout<<'F'<< endl; 96 | } else { 97 | if (grade < 70) { 98 | cout<<'D'<< endl; 99 | } else { 100 | if (grade < 80) { 101 | cout<<'C'<< endl; 102 | } else { 103 | if (grade < 90) { 104 | cout<<'B'<< endl; 105 | } else { 106 | cout<<'A'<< endl; 107 | } 108 | 109 | return 0; 110 | } 111 | } 112 | } 113 | } 114 | 115 | We can get even closer to the elif statement by taking advantage of the 116 | C++ rule that a single statement does not need to be enclosed in curly 117 | braces. Since the if is the only statement used in each else we can get 118 | away with the following. 119 | 120 | .. activecode:: C++elif2 121 | :language: C++ 122 | :sourcefile: ElseIf.cpp 123 | 124 | #include 125 | using namespace std; 126 | 127 | int main() { 128 | 129 | int grade = 85; 130 | if (grade < 60) { 131 | cout<<'F'< 155 | using namespace std; 156 | 157 | int main() { 158 | 159 | int grade = 85; 160 | 161 | int tempgrade = grade / 10; 162 | switch(tempgrade) { 163 | case 10: 164 | case 9: 165 | cout<<'A'< 2 | Summary and Reading Questions 3 |

      4 |
    1. 5 |

      6 | A statically allocated C++ array is an ordered collection of one or more C++ data values of identical type stored in contiguous memory. 7 |

      8 |
    2. 9 |
    3. 10 |

      11 | A vector is a dynamically allocated array with many useful methods. It is more similar to the Python list than the array. 12 |

      13 |
    4. 14 |
    5. 15 |

      16 | C++ strings are a sequential collection of zero or more characters. They are very similar to Python strings. 17 |

      18 |
    6. 19 |
    7. 20 |

      21 | 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. 22 |

      23 |
    8. 24 |
    9. 25 |

      26 | A set is an unordered collection of unique values. 27 |

      28 |
    10. 29 |

    30 | 31 | Reading Questions 32 | 33 | 34 | 35 |

    Which C++ structure is the best choice for a group of ordered data of a fixed length?

    36 | 37 |
    38 | 39 | 40 | 41 | 42 |

    array

    43 |
    44 | 45 |

    Correct!

    46 |
    47 |
    48 | 49 | 50 | 51 |

    hash table

    52 |
    53 | 54 |

    No. hash tables are not ordered. 55 |

    56 |
    57 |
    58 | 59 | 60 |

    string

    61 |
    62 | 63 |

    A string would only work for character data. Try again. 64 |

    65 |
    66 |
    67 | 68 | 69 |

    vector

    70 |
    71 | 72 |

    There is a better choice given that the group is fixed length. 73 |

    74 |
    75 |
    76 | 77 | 78 |

    more than one of the above

    79 |
    80 | 81 |

    Only of the above is best. 82 |

    83 |
    84 |
    85 |
    86 |
    87 | 88 |

    Drag each data type to its' corresponding C++ initialization syntax.

    89 |

    Feedback shows incorrect matches.

    90 | 91 | Array{“What”, “am”, “I”, "am"}Set{“What”, “am”, “I”}String“What am I” 92 | Hash Table{​{“What”, “am I”}​} 93 | 94 |
    95 | 96 | 97 |

    Match the words to thier corresponding definition.

    98 |

    Feedback shows incorrect matches.

    99 | stringA sequential data structure consisting of zero or more characters.collection a grouping of a number of data items that have some shared significance or need to be operated upon together.vectorsequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.hash tablea collection consisting of key-value pairs with an associated function that maps the key to the associated value.
    100 | 101 | 102 |

    Match the words to thier corresponding definition.

    103 |

    Feedback shows incorrect matches.

    104 | 105 | arraya data structure consisting of an ordered collection of data elements of identical type in which each element can be identified by an index. 106 | wordunit of data used by a particular processor design.mutabilityable to be modified.immutableunable to be modified. 107 | setAn unordered data structure consisting of unique, immutable data values. 108 | 109 |
    110 |
    111 | 112 | 113 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | all: html 20 | 21 | help: 22 | @echo "Please use \`make ' where is one of" 23 | @echo " html to make standalone HTML files" 24 | @echo " dirhtml to make HTML files named index.html in directories" 25 | @echo " singlehtml to make a single large HTML file" 26 | @echo " pickle to make pickle files" 27 | @echo " json to make JSON files" 28 | @echo " htmlhelp to make HTML files and a HTML help project" 29 | @echo " qthelp to make HTML files and a qthelp project" 30 | @echo " devhelp to make HTML files and a Devhelp project" 31 | @echo " epub to make an epub" 32 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 33 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " linkcheck to check all external links for integrity" 41 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 42 | 43 | 44 | 45 | clean: 46 | -rm -rf $(BUILDDIR)/* 47 | 48 | html: 49 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 50 | @echo 51 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 52 | 53 | dirhtml: 54 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 55 | @echo 56 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 57 | 58 | singlehtml: 59 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 60 | @echo 61 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 62 | 63 | pickle: 64 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 65 | @echo 66 | @echo "Build finished; now you can process the pickle files." 67 | 68 | json: 69 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 70 | @echo 71 | @echo "Build finished; now you can process the JSON files." 72 | 73 | htmlhelp: 74 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 75 | @echo 76 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 77 | ".hhp project file in $(BUILDDIR)/htmlhelp." 78 | 79 | qthelp: 80 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 81 | @echo 82 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 83 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 84 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/CppforPythonProgrammers.qhcp" 85 | @echo "To view the help file:" 86 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/CppforPythonProgrammers.qhc" 87 | 88 | devhelp: 89 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 90 | @echo 91 | @echo "Build finished." 92 | @echo "To view the help file:" 93 | @echo "# mkdir -p $$HOME/.local/share/devhelp/CppforPythonProgrammers" 94 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/CppforPythonProgrammers" 95 | @echo "# devhelp" 96 | 97 | epub: 98 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 99 | @echo 100 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 101 | 102 | latex: 103 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 104 | @echo 105 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 106 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 107 | "(use \`make latexpdf' here to do that automatically)." 108 | 109 | latexpdf: 110 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 111 | @echo "Running LaTeX files through pdflatex..." 112 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 113 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 114 | 115 | text: 116 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 117 | @echo 118 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 119 | 120 | man: 121 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 122 | @echo 123 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 124 | 125 | texinfo: 126 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 127 | @echo 128 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 129 | @echo "Run \`make' in that directory to run these through makeinfo" \ 130 | "(use \`make info' here to do that automatically)." 131 | 132 | info: 133 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 134 | @echo "Running Texinfo files through makeinfo..." 135 | make -C $(BUILDDIR)/texinfo info 136 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 137 | 138 | gettext: 139 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 140 | @echo 141 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 142 | 143 | changes: 144 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 145 | @echo 146 | @echo "The overview file is in $(BUILDDIR)/changes." 147 | 148 | linkcheck: 149 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 150 | @echo 151 | @echo "Link check complete; look for any errors in the above output " \ 152 | "or in $(BUILDDIR)/linkcheck/output.txt." 153 | 154 | doctest: 155 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 156 | @echo "Testing of doctests in the sources finished, look at the " \ 157 | "results in $(BUILDDIR)/doctest/output.txt." 158 | -------------------------------------------------------------------------------- /_sources/CollectionData/UnorderedSet.rst: -------------------------------------------------------------------------------- 1 | .. Copyright (C) Jan Pearce 2 | This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. 3 | 4 | 5 | Unordered Sets 6 | ^^^^^^^^^^^^^^ 7 | 8 | An **unordered_set** is an unordered collection of zero or more unique C++ data values 9 | of a particular type. 10 | To use unordered_sets, you import ``unordered_set`` from the Standard template library with 11 | ``#include ``. 12 | 13 | Unordered_sets allow for fast retrieval of individual elements based on their value. 14 | In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. 15 | ``Keys`` are **immutable**, therefore, the elements in an ``unordered_set`` cannot be modified once in the container - 16 | However, they can be inserted and removed. 17 | 18 | 19 | Unordered sets do not allow duplicates and are initialized using comma-delimited 20 | values enclosed in curly braces. The collection can be assigned to 21 | a variable as shown below. 22 | 23 | 24 | :: 25 | 26 | set mySet = {3, 6, 4, 78, 10} 27 | 28 | 29 | Unordered sets support a number of methods that should be familiar to those who 30 | have worked with sets in a mathematics setting. :ref:`Table 6 ` 31 | provides a summary. Examples of their use follow. 32 | 33 | .. _tab_setmethods: 34 | 35 | .. table:: **Table 6: Methods Provided by Sets in C++** 36 | 37 | ======================== ================================= ================================================================ 38 | **Method Name** **Use** **Explanation** 39 | ======================== ================================= ================================================================ 40 | ``union`` ``set_union()`` Returns a new set with all elements from both sets 41 | ``intersection`` ``set_intersection()`` Returns a new set with only those elements common to both sets 42 | ``difference`` ``set_difference()`` Returns a new set with all items from first set not in second 43 | ``insert`` ``aset.insert(item)`` Adds item to the set 44 | ``erase`` ``aset.erase(item)`` Removes item from the set 45 | ``clear`` ``aset.clear()`` Removes all elements from the set 46 | ``find`` ``aset.find(item)`` Find item in the set 47 | ======================== ================================= ================================================================ 48 | 49 | The code below is an example of a program that can detect if a specific char is in an unordered set. 50 | 51 | .. activecode:: Unordered_set_example 52 | :language: cpp 53 | 54 | // Function that checks to see if a char 55 | // is in the unorderd set 56 | #include 57 | #include 58 | using namespace std; 59 | 60 | void checker(unordered_set set, char letter){ 61 | if(set.find(letter) == set.end()){ 62 | cout << "letter " << letter << " is not in the set." << endl; 63 | } 64 | else{ 65 | cout << "letter " << letter << " is in the set." << endl; 66 | } 67 | } 68 | 69 | int main(){ 70 | unordered_set charSet = {'d', 'c', 'b', 'a'}; 71 | 72 | char letter = 'e'; 73 | checker(charSet, letter); 74 | charSet.insert('e'); 75 | checker(charSet, letter); 76 | return 0; 77 | } 78 | 79 | the ``find`` method used for a conditional in ``Checker`` compares 80 | each item in the set with the given parameter until there is a match. the 81 | ``set.find(letter) == set.end()`` section means that if ``find`` cannot 82 | find the ``letter`` before reaching the end of the set, then ``letter`` 83 | is not contained in the set. 84 | 85 | Matching 86 | ======== 87 | .. dragndrop:: matching_us 88 | :feedback: Feedback shows incorrect matches. 89 | :match_1: union|||Returns a new set with all elements from both sets. 90 | :match_2: intersection|||Returns a new set with only those elements common to both sets. 91 | :match_3: difference||| Returns a new set with all items from first set not in second. 92 | :match_4: add|||Adds item to the set. 93 | :match_5: remove|||erases item from the set. 94 | :match_6: clear|||Removes all elements from the set. 95 | 96 | Match the Unordered Sets operations with their corresponding explination. 97 | 98 | 99 | Summary 100 | ^^^^^^^ 101 | 102 | 1. A statically allocated C++ array is an ordered collection of one or more C++ data values of identical type stored in contiguous memory. 103 | 104 | 2. A vector is a dynamically allocated array with many useful methods. It is more similar to the Python list than the array. 105 | 106 | 3. C++ strings are a sequential collection of zero or more characters. They are very similar to Python strings. 107 | 108 | 4. 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. 109 | 110 | 5. A set is an unordered collection of unique values. 111 | 112 | 113 | Check Yourself 114 | ^^^^^^^^^^^^^^ 115 | 116 | 117 | .. mchoice:: mc_fixed 118 | :answer_a: array 119 | :answer_b: hash table 120 | :answer_c: string 121 | :answer_d: vector 122 | :answer_e: more than one of the above 123 | :correct: a 124 | :feedback_a: Correct! 125 | :feedback_b: No. hash tables are not ordered. 126 | :feedback_c: A string would only work for character data. Try again. 127 | :feedback_d: There is a better choice given that the group is fixed length 128 | :feedback_e: Only of the above is best. 129 | 130 | Which C++ structure is the best choice for a group of ordered data of a fixed length? 131 | 132 | 133 | 134 | .. dragndrop:: collect_data_types 135 | :feedback: Feedback shows incorrect matches. 136 | :match_1: Array|||{“What”, “am”, “I”, "am"} 137 | :match_2: Set|||{“What”, “am”, “I”} 138 | :match_3: String|||“What am I” 139 | :match_4: Hash Table|||{​{“What”, “am I”}​} 140 | 141 | Drag each data type to its' corresponding C++ initialization syntax. 142 | --------------------------------------------------------------------------------