0% found this document useful (0 votes)
19 views

C++ Menu: C++ Output (Print Text)

The document provides a detailed guide to C++ including explanations of syntax, output, comments, variables, data types, operators, strings, math, conditions, loops, arrays, structures, functions and more. Each concept is accompanied by examples and explanations spanning multiple pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

C++ Menu: C++ Output (Print Text)

The document provides a detailed guide to C++ including explanations of syntax, output, comments, variables, data types, operators, strings, math, conditions, loops, arrays, structures, functions and more. Each concept is accompanied by examples and explanations spanning multiple pages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

‭0‬

‭C++ Function Overloading 78-79‬

‭C++ Menu‬
‭C++ Recursion‬ ‭79-81‬
‭C++ Classes‬
‭C++ OOP‬ ‭81-83‬
‭Title‬ ‭page‬‭number‬
‭C++ Classes/Objects‬ ‭83-87‬
‭C++ Syntax‬ ‭2-3‬ ‭C++ Class Methods‬ ‭87-89‬
‭C++ Output‬ ‭4-7‬ ‭C++ Constructors 89-93‬
‭C++ Comments‬ ‭7-8‬ ‭C++ Access Specifiers 93-95‬

‭C++‬
‭C++ Variables‬ ‭8-13‬ ‭C++ Encapsulation 95-97‬
‭C++ User Input‬ ‭13-14‬ ‭C++ Inheritance 97-102‬
‭C++ Data Types‬ ‭14-18‬ ‭C++ Polymorphism 102-105‬
‭C++ Operators‬ ‭18-22‬ ‭C++ Files 105-107‬
‭C++ Strings‬ ‭23-30‬ ‭C++ Exceptions 108-111‬
‭C++ Math‬ ‭30-32‬ ‭Add Two Numbers 111-112‬
‭C++ Booleans‬ ‭32-34‬ ‭C++ Reference‬
‭C++ Conditions(if……else)‬ ‭35-39‬ ‭C++ Keywords 112-115‬
‭C++ Switch‬ ‭39-42‬ ‭C++ Math Functions 115-118‬
‭A complete guide to‬ ‭C++ While Loop‬ ‭42-44‬
‭C++ For Loop‬ ‭44-46‬ ‭C++ Syntax‬
‭c++‬
‭C++ Break/Continue‬ ‭46-48‬
‭C++ Arrays‬ ‭48-59‬ ‭C++ Syntax‬
‭ et's break up the following code to understand it better:‬
L
‭C++ Structures‬ ‭59-63‬ ‭Example‬
‭C++ References‬ ‭63-64‬ ‭#include <iostream>‬
‭C++ Pointers‬ ‭64-67‬ ‭using namespace std;‬
‭C++ Functions‬ ‭67-71‬ ‭int main() {‬
‭C++ Function Parameters‬ ‭71-77‬ ‭cout << "Hello World!";‬
‭1‬ ‭2‬

‭return 0;‬ ‭Line 7: Do not forget to add the closing curly bracket } to actually end the main‬ ‭You can add as many cout objects as you want. However, note that it does not‬
‭}‬ ‭function.‬ ‭insert a new line at the end of the output:‬
‭Example explained‬ ‭Omitting Namespace‬ ‭Example‬
‭Line 1: #include <iostream> is a header file library that lets us work with input‬ ‭You might see some C++ programs that runs without the standard namespace‬ ‭#include <iostream>‬
‭and output objects, such as cout (used in line 5). Header files add functionality to‬ ‭library. The using namespace std line can be omitted and replaced with the std‬ ‭using namespace std;‬
‭C++ programs.‬ ‭keyword, followed by the :: operator for some objects:‬ ‭int main() {‬
‭Line 2: using namespace std means that we can use names for objects and‬ ‭Example‬ ‭cout << "Hello World!";‬
‭variables from the standard library.‬ ‭#include <iostream>‬ ‭cout << "I am learning C++";‬

‭int main() {‬ ‭return 0;‬


‭Don't worry if you don't understand how #include <iostream> and using‬ ‭std::cout << "Hello World!";‬ ‭}‬
‭namespace std works. Just think of it as something that (almost) always appears‬ ‭return 0;‬ ‭C++ New Lines‬
‭in your program.‬ ‭}‬ ‭New Lines‬

‭It is up to you if you want to include the standard namespace library or not.‬ ‭To insert a new line, you can use the \n character:‬
‭Line 3: A blank line. C++ ignores white space. But we use it to make the code‬ ‭Example‬
‭more readable.‬ ‭C++ Output (Print Text)‬ ‭#include <iostream>‬
‭Line 4: Another thing that always appear in a C++ program is int main(). This is‬ ‭using namespace std;‬
‭C++ Output (Print Text)‬
‭called a function. Any code inside its curly brackets {} will be executed.‬ ‭int main() {‬
‭The cout object, together with the << operator, is used to output values/print‬
‭Line 5: cout (pronounced "see-out") is an object used together with the insertion‬ ‭cout << "Hello World! \n";‬
‭text:‬
‭operator (<<) to output/print text. In our example, it will output "Hello World!".‬ ‭cout << "I am learning C++";‬
‭Example‬
‭Note: Every C++ statement ends with a semicolon ;.‬ ‭return 0;‬
‭#include <iostream>‬
‭Note: The body of int main() could also been written as:‬ ‭}‬
‭using namespace std;‬
‭int main () { cout << "Hello world! "; return 0; }‬ ‭Tip : Two \n characters after each other will create a blank line:‬
‭int main() {‬
‭Remember: The compiler ignores white spaces. However, multiple lines makes‬
‭cout << "Hello World!";‬
‭the code more readable.‬ ‭Example‬
‭return 0; }‬
‭Line 6: return 0 ends the main function.‬ ‭#include <iostream>‬

‭3‬ ‭4‬ ‭5‬

‭using namespace std;‬ ‭\t‬ ‭Creates a horizontal tab‬ ‭/* The code below will print the words Hello World!‬
‭int main() {‬ ‭\\‬ ‭Inserts a backslash character (\)‬ ‭to the screen, and it is amazing */‬
‭cout << "Hello World! \n\n";‬ ‭\"‬ ‭Inserts a double quote character‬ ‭cout << "Hello World!";‬
‭cout << "I am learning C++";‬ ‭Single or multi-line comments?‬
‭return 0;‬ ‭C++ Comments‬ ‭It is up to you which you want to use. Normally, we use // for short comments,‬
‭}‬ ‭and /* */ for longer.‬
‭C++ Comments‬
‭Another way to insert a new line, is with the endl manipulator:‬
‭Example‬
‭Comments can be used to explain C++ code, and to make it more readable. It can‬ ‭C++ Variables‬
‭also be used to prevent execution when testing alternative code. Comments can‬
‭#include <iostream>‬
‭be single-lined or multi-lined.‬ ‭C++ Variables‬
‭using namespace std;‬
‭Variables are containers for storing data values.‬
‭int main() {‬
‭Single-line Comments‬ ‭In C++, there are different types of variables (defined with different keywords),‬
‭cout << "Hello World!" << endl;‬
‭Single-line comments start with two forward slashes (//).‬ ‭for example:‬
‭cout << "I am learning C++";‬
‭Any text between // and the end of the line is ignored by the compiler (will not‬ ‭int - stores integers (whole numbers), without decimals, such as 123 or -123‬
‭return 0;‬
‭be executed).‬ ‭double - stores floating point numbers, with decimals, such as 19.99 or -19.99‬
‭}‬
‭This example uses a single-line comment before a line of code:‬ ‭char - stores single characters, such as 'a' or 'B'. Char values are surrounded by‬
‭Both \n and endl are used to break lines. However, \n is most used.‬
‭Example‬ ‭single quotes‬
‭// This is a comment‬ ‭string - stores text, such as "Hello World". String values are surrounded by‬
‭But what is \n exactly?‬
‭cout << "Hello World!";‬ ‭double quotes‬
‭The newline character (\n) is called an escape sequence, and it forces the cursor‬
‭This example uses a single-line comment at the end of a line of code:‬ ‭bool - stores values with two states: true or false‬
‭to change its position to the beginning of the next line on the screen. This‬
‭Example‬
‭results in a new line.‬
‭cout << "Hello World!"; // This is a comment‬ ‭Declaring (Creating) Variables‬
‭C++ Multi-line Comments‬ ‭To create a variable, specify the type and assign it a value:‬
‭Examples of other valid escape sequences are:‬
‭Multi-line comments start with /* and ends with */.‬ ‭Syntax‬
‭Any text between /* and */ will be ignored by the compiler:‬ ‭type variableName = value;‬
‭Escape Sequence‬ ‭description‬
‭Example‬
‭6‬ ‭7‬ ‭8‬
‭Where type is one of C++ types (such as int), and variableName is the name of‬ ‭int myNum = 5; // Integer (whole number without decimals)‬ ‭Example‬
‭the variable (such as x or myName). The equal sign is used to assign values to the‬ ‭double myFloatNum = 5.99; // Floating point number (with decimals)‬ ‭int x = 5, y = 6, z = 50;‬
‭variable.‬ ‭char myLetter = 'D'; // Character‬ ‭cout << x + y + z;‬
‭To create a variable that should store a number, look at the following example:‬ ‭string myText = "Hello"; // String (text)‬ ‭One Value to Multiple Variables‬
‭Example‬ ‭bool myBoolean = true; // Boolean (true or false)‬ ‭You can also assign the same value to multiple variables in one line:‬
‭Create a variable called myNum of type int and assign it the value 15:‬ ‭You will learn more about the individual types in the Data Types chapter.‬ ‭Example‬
‭int myNum = 15;‬ ‭int x, y, z;‬
‭cout << myNum;‬ ‭Display Variables‬ ‭x = y = z = 50;‬
‭You can also declare a variable without assigning the value, and assign the value‬ ‭The cout object is used together with the << operator to display variables.‬ ‭cout << x + y + z;‬
‭later:‬ ‭To combine both text and a variable, separate them with the << operator:‬
‭Example‬ ‭C++ Identifiers‬
‭int myNum;‬ ‭Example‬ ‭C++ Identifiers‬
‭myNum = 15;‬ ‭int myAge = 35;‬ ‭All C++ variables must be identified with unique names.‬
‭cout << myNum;‬ ‭cout << "I am " << myAge << " years old.";‬ ‭These unique names are called identifiers.‬
‭Note that if you assign a new value to an existing variable, it will overwrite the‬ ‭Add Variables Together‬ ‭Identifiers can be short names (like x and y) or more descriptive names (age,‬
‭previous value:‬ ‭To add a variable to another variable, you can use the + operator:‬ ‭sum, totalVolume).‬
‭Example‬
‭Example‬ ‭int x = 5;‬ ‭Note: It is recommended to use descriptive names in order to create‬
‭int myNum = 15; // myNum is 15‬ ‭int y = 6;‬ ‭understandable and maintainable code:‬
‭myNum = 10; // Now myNum is 10‬ ‭int sum = x + y;‬ ‭Example‬
‭cout << myNum; // Outputs 10‬ ‭cout << sum;‬ ‭// Good‬
‭Other Types‬ ‭int minutesPerHour = 60;‬
‭A demonstration of other data types:‬ ‭C++ Declare Multiple Variables‬ ‭// OK, but not so easy to understand what m actually is‬
‭Declare Many Variables‬ ‭int m = 60;‬
‭Example‬ ‭To declare more than one variable of the same type, use a comma-separated list:‬ ‭The general rules for naming variables are:‬

‭9‬ ‭10‬ ‭11‬

‭This however, will not work:‬ ‭In this example, the user must input two numbers. Then we print the sum by‬
‭Names can contain letters, digits and underscores‬ ‭const int minutesPerHour;‬ ‭calculating (adding) the two numbers:‬
‭Names must begin with a letter or an underscore (_)‬ ‭minutesPerHour = 60; // error‬
‭Names are case-sensitive (myVar and myvar are different variables)‬
‭C++ User Input‬
‭Example‬
‭Names cannot contain whitespaces or special characters like !, #, %, etc.‬ ‭int x, y;‬
‭Reserved words (like C++ keywords, such as int) cannot be used as names‬ ‭int sum;‬
‭C++ User Input‬

‭C++ Constants‬
‭cout << "Type a number: ";‬
‭You have already learned that cout is used to output (print) values. Now we will‬
‭cin >> x;‬
‭use cin to get user input.‬
‭cout << "Type another number: ";‬
‭Constants‬ ‭cin is a predefined variable that reads data from the keyboard with the‬
‭cin >> y;‬
‭When you do not want others (or yourself) to change existing variable values, use‬ ‭extraction operator (>>).‬
‭sum = x + y;‬
‭the const keyword (this will declare the variable as "constant", which means‬ ‭In the following example, the user can input a number, which is stored in the‬
‭cout << "Sum is: " << sum;‬
‭unchangeable and read-only):‬ ‭variable x. Then we print the value of x:‬
‭Example‬
‭const int myNum = 15; // myNum will always be 15‬
‭Example‬
‭int x;‬
‭C++ Data Types‬
‭myNum = 10; // error: assignment of read-only variable 'myNum'‬ ‭cout << "Type a number: "; // Type a number and press enter‬ ‭C++ Data Types‬
‭You should always declare the variable as constant when you have values that‬ ‭cin >> x; // Get user input from the keyboard‬ ‭As explained in the Variables chapter, a variable in C++ must be a specified data‬
‭are unlikely to change:‬ ‭cout << "Your number is: " << x; // Display the input value‬ ‭type:‬
‭Example‬ ‭Good To Know‬ ‭Example‬
‭const int minutesPerHour = 60;‬ ‭int myNum = 5; // Integer (whole number)‬
‭const float PI = 3.14;‬ ‭cout is pronounced "see-out". Used for output, and uses the insertion operator‬ ‭float myFloatNum = 5.99; // Floating point number‬
‭Notes On Constants‬ ‭(<<)‬ ‭double myDoubleNum = 9.98; // Floating point number‬
‭When you declare a constant variable, it must be assigned with a value:‬ ‭cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)‬ ‭char myLetter = 'D'; // Character‬
‭Example‬ ‭bool myBoolean = true; // Boolean‬
‭Like this:‬ ‭Creating a Simple Calculator‬ ‭string myText = "Hello"; // String‬
‭const int minutesPerHour = 60;‬ ‭Basic Data Types‬

‭12‬ ‭13‬ ‭14‬

‭The data type specifies the size and type of information the variable will store:‬ ‭double myNum = 19.99;‬ ‭Example‬
‭cout << myNum;‬ ‭bool isCodingFun = true;‬

‭Data Type‬ ‭Size‬ ‭Description‬ ‭float vs. double‬ ‭bool isFishTasty = false;‬
‭cout << isCodingFun; // Outputs 1 (true)‬
‭boolean‬ ‭1 byte‬ ‭Stores true or false values‬
‭The precision of a floating point value indicates how many digits the value can‬ ‭cout << isFishTasty; // Outputs 0 (false)‬
‭char‬ ‭1 byte‬ ‭Stores a single character/letter/number, or‬
‭have after the decimal point. The precision of float is only six or seven decimal‬ ‭Boolean values are mostly used for conditional testing‬
‭ASCII values‬
‭digits, while double variables have a precision of about 15 digits. Therefore it is‬
‭int‬ ‭2 or 4 bytes‬ ‭Stores whole numbers, without decimals‬
‭safer to use double for most calculations.‬ ‭C++ Character Data Types‬
‭float‬ ‭4 bytes‬ ‭Stores fractional numbers, containing one or more‬
‭decimals. Sufficient for storing 6-7 decimal digits‬ ‭Character Types‬
‭Scientific Numbers‬ ‭The char data type is used to store a single character. The character must be‬
‭double‬ ‭8 bytes‬ ‭Stores fractional numbers, containing one or more‬
‭A floating point number can also be a scientific number with an "e" to indicate‬ ‭surrounded by single quotes, like 'A' or 'c':‬
‭decimals. Sufficient for storing 15 decimal digits‬
‭the power of 10:‬ ‭Example‬
‭C++ Numeric Data Types‬ ‭char myGrade = 'B';‬
‭Example‬ ‭cout << myGrade;‬
‭Numeric Types‬
‭float f1 = 35e3;‬ ‭Alternatively, if you are familiar with ASCII, you can use ASCII values to display‬
‭Use int when you need to store a whole number without decimals, like 35 or‬
‭double d1 = 12E4;‬ ‭certain characters:‬
‭1000, and float or double when you need a floating point number (with‬
‭cout << f1;‬ ‭Example‬
‭decimals), like 9.99 or 3.14515.‬
‭cout << d1;‬ ‭char a = 65, b = 66, c = 67;‬

‭Int‬ ‭C++ Boolean Data Types‬ ‭cout << a;‬


‭cout << b;‬
‭int myNum = 1000;‬
‭Boolean Types‬ ‭cout << c;‬
‭cout << myNum;‬
‭A boolean data type is declared with the bool keyword and can only take the‬ ‭Tip: A list of all ASCII values can be found in our ASCII Table Reference.‬
‭float‬
‭float myNum = 5.75;‬ ‭values true or false.‬
‭When the value is returned, true = 1 and false = 0.‬
‭C++ String Data Types‬
‭cout << myNum;‬
‭Double‬ ‭String Types‬

‭15‬ ‭16‬ ‭17‬


‭The string type is used to store a sequence of characters (text). This is not a‬ ‭Although the + operator is often used to add together two values, like in the‬ ‭/‬ ‭Division‬ ‭Divides one value by another‬
‭built-in type, but it behaves like one in its most basic usage. String values must‬ ‭example above, it can also be used to add together a variable and a value, or a‬ ‭x / y‬
‭be surrounded by double quotes:‬ ‭variable and another variable:‬ ‭%‬ ‭Modulus‬ ‭Returns the division remainder‬
‭Example‬ ‭x % y‬
‭Example‬ ‭int sum1 = 100 + 50; // 150 (100 + 50)‬ ‭++‬ ‭Increment‬ ‭Increases the value of a variable by‬
‭string greeting = "Hello";‬ ‭int sum2 = sum1 + 250; // 400 (150 + 250)‬ ‭1++x‬
‭cout << greeting;‬ ‭int sum3 = sum2 + sum2; // 800 (400 + 400)‬ ‭--‬ ‭Decrement‬ ‭Decreases the value of a variable by‬
‭To use strings, you must include an additional header file in the source code, the‬ ‭C++ divides the operators into the following groups:‬ ‭1--x‬
‭<string> library:‬ ‭Arithmetic operators‬
‭Assignment operators‬ ‭C++ Assignment Operators‬
‭Example‬ ‭Comparison operators‬
‭Assignment Operators‬
‭// Include the string library‬ ‭Logical operators‬
‭Assignment operators are used to assign values to variables.‬
‭#include <string>‬ ‭Bitwise operators‬
‭In the example below, we use the assignment operator (=) to assign the value 10‬
‭// Create a string variable‬ ‭Arithmetic Operators‬
‭to a variable called x:‬
‭string greeting = "Hello";‬
‭Example‬
‭// Output string value‬ ‭Arithmetic operators are used to perform common mathematical operations.‬
‭int x = 10;‬
‭cout << greeting;‬
‭The addition assignment operator (+=) adds a value to a variable:‬

‭C++ Operators‬
‭Operator‬ ‭Name‬ ‭Description‬
‭Example‬
‭Example‬
‭int x = 10;‬
‭C++ Operators‬ ‭+‬ ‭Addition‬ ‭Adds together two values‬
‭x += 5;‬
‭Operators are used to perform operations on variables and values.‬ ‭x + y‬
‭A list of all assignment operators:‬
‭In the example below, we use the + operator to add together two values:‬ ‭-‬ ‭Subtraction‬ ‭Subtracts one value from another‬

‭Example‬ ‭x - y‬
‭Operator‬ ‭Example‬ ‭Same As‬
‭int x = 100 + 50;‬ ‭*‬ ‭Multiplication‬ ‭Multiplies two values‬
‭=‬ ‭x = 5‬ ‭x = 5‬
‭x * y‬
‭+=‬ ‭x += 3‬ ‭x = x + 3‬

‭18‬ ‭19‬ ‭20‬

‭-=‬ ‭x -= 3‬ ‭x = x - 3‬ ‭C++ Strings‬


‭*=‬ ‭x *= 3‬ ‭x = x * 3‬ ‭Operator‬ ‭Name‬ ‭Example‬ ‭Strings are used for storing text.‬
‭/=‬ ‭x /= 3‬ ‭x = x / 3‬ ‭==‬ ‭Equal to‬ ‭x == y‬ ‭A string variable contains a collection of characters surrounded by double‬
‭%=‬ ‭x %= 3‬ ‭x = x % 3‬ ‭!=‬ ‭Not equal‬ ‭x != y‬ ‭quotes:‬
‭&=‬ ‭x &= 3‬ ‭x = x & 3‬ ‭>‬ ‭Greater than‬ ‭x > y‬
‭|=‬ ‭x |= 3‬ ‭x = x | 3‬ ‭<‬ ‭Less than‬ ‭x < y‬ ‭Example‬
‭^=‬ ‭x ^= 3‬ ‭x = x ^ 3‬ ‭>=‬ ‭Greater than or equal to‬ ‭x >= y‬ ‭Create a variable of type string and assign it a value:‬
‭>>=‬ ‭x >>= 3‬ ‭x = x >> 3‬ ‭<=‬ ‭Less than or equal to‬ ‭x <= y‬ ‭string greeting = "Hello";‬
‭<<=‬ ‭x <<= 3‬ ‭x = x << 3‬
‭C++ Logical Operators‬
‭To use strings, you must include an additional header file in the source code, the‬

‭C++ Comparison Operators‬


‭<string> library:‬

‭Logical Operators‬
‭Example‬
‭Comparison Operators‬ ‭As with comparison operators, you can also test for true (1) or false (0) values‬
‭// Include the string library‬
‭Comparison operators are used to compare two values (or variables). This is‬ ‭with logical operators.‬
‭#include <string>‬
‭important in programming, because it helps us to find answers and make‬ ‭Logical operators are used to determine the logic between variables or values:‬
‭// Create a string variable‬
‭decisions.‬
‭string greeting = "Hello";‬
‭The return value of a comparison is either 1 or 0, which means true (1) or false‬ ‭Operator‬ ‭Name‬ ‭Description‬
‭(0). These values are known as Boolean values, and you will learn more about‬
‭them in the Booleans and If..Else chapter.‬ ‭&&‬
‭Example‬
‭Logical and‬ ‭Returns true if both statements are true‬
‭C++ String Concatenation‬
‭In the following example, we use the greater than operator (>) to find out if 5 is‬ ‭x < 5 && x < 10‬ ‭String Concatenation‬
‭greater than 3:‬ ‭||‬ ‭Logical or‬ ‭Returns true if one of the statements is true‬ ‭The + operator can be used between strings to add them together to make a new‬
‭Example‬ ‭x < 5 || x < 4‬ ‭string. This is called concatenation:‬
‭int x = 5;‬ ‭!‬ ‭Logical not‬ ‭Reverse the result, returns false if the result is true‬ ‭Example‬
‭int y = 3;‬ ‭!(x < 5‬ ‭string firstName = "John ";‬
‭cout << (x > y); // returns 1 (true) because 5 is greater than 3‬
‭C++ Strings‬
‭string lastName = "Doe";‬
‭A list of all comparison operators:‬ ‭string fullName = firstName + lastName;‬

‭21‬ ‭22‬ ‭23‬

‭cout << fullName;‬ ‭Numbers are added. Strings are concatenated.‬ ‭Tip: You might see some C++ programs that use the size() function to get the‬
‭In the example above, we added a space after firstName to create a space‬ ‭If you add two numbers, the result will be a number:‬ ‭length of a string. This is just an alias of length(). It is completely up to you if‬
‭between John and Doe on output. However, you could also add a space with‬ ‭Example‬ ‭you want to use length() or size():‬
‭quotes (" " or ' '):‬ ‭int x = 10;‬ ‭Example‬
‭Example‬ ‭int y = 20;‬ ‭string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";‬
‭string firstName = "John";‬ ‭int z = x + y; // z will be 30 (an integer)‬ ‭cout << "The length of the txt string is: " << txt.size();‬
‭string lastName = "Doe";‬ ‭If you add two strings, the result will be a string concatenation:‬
‭string fullName = firstName + " " + lastName;‬ ‭Example‬ ‭C++ Access Strings‬
‭cout << fullName;‬ ‭string x = "10";‬
‭Access Strings‬
‭Append‬ ‭string y = "20";‬
‭You can access the characters in a string by referring to its index number inside‬
‭A string in C++ is actually an object, which contain functions that can perform‬ ‭string z = x + y; // z will be 1020 (a string)‬
‭square brackets [ ].‬
‭certain operations on strings. For example, you can also concatenate strings‬ ‭If you try to add a number to a string, an error occurs:‬
‭This example prints the first character in myString:‬
‭with the append() function:‬ ‭Example‬
‭Example‬
‭Example‬ ‭string x = "10";‬
‭string myString = "Hello";‬
‭string firstName = "John ";‬ ‭int y = 20;‬
‭cout << myString[0];‬
‭string lastName = "Doe";‬ ‭string z = x + y;‬
‭// Outputs H‬
‭string fullName = firstName.append(lastName);‬
‭cout << fullName;‬ ‭C++ String Length‬ ‭Note: String indexes start with 0: [0] is the first character. [1] is the second‬
‭character, etc.‬

‭C++ Numbers and Strings‬ ‭String Length‬


‭To get the length of a string, use the length() function:‬ ‭This example prints the second character in myString:‬
‭Adding Numbers and Strings‬ ‭Example‬ ‭Example‬
‭WARNING!‬ ‭string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";‬ ‭string myString = "Hello";‬
‭cout << "The length of the txt string is: " << txt.length();‬ ‭cout << myString[1];‬
‭C++ uses the + operator for both addition and concatenation.‬ ‭// Outputs e‬
‭Change String Characters‬

‭24‬ ‭25‬ ‭26‬


‭To change the value of a specific character in a string, refer to the index number,‬ ‭Example‬ ‭string fullName;‬
‭and use single quotes:‬ ‭string txt = "It\'s alright.";‬ ‭cout << "Type your full name: ";‬
‭Example‬ ‭The sequence \\ inserts a single backslash in a string:‬ ‭cin >> fullName;‬
‭string myString = "Hello";‬ ‭Example‬ ‭cout << "Your name is: " << fullName;‬
‭myString[0] = 'J';‬ ‭string txt = "The character \\ is called backslash.";‬ ‭// Type your full name: John Doe‬
‭cout << myString;‬ ‭Other popular escape characters in C++ are:‬ ‭// Your name is: John‬
‭// Outputs Jello instead of Hello‬ ‭From the example above, you would expect the program to print "John Doe", but‬

‭C++ Special Characters‬


‭Escape Character‬ ‭Result‬ ‭it only prints "John".‬
‭\n‬ ‭New Line‬ ‭That's why, when working with strings, we often use the getline() function to‬
‭\t‬ ‭Tab‬ ‭read a line of text. It takes cin as the first parameter, and the string variable as‬
‭Strings - Special Characters‬

‭C++ User Input Strings‬


‭second:‬
‭Because strings must be written within quotes, C++ will misunderstand this‬
‭Example‬
‭string, and generate an error:‬
‭string fullName;‬
‭string txt = "We are the so-called "Vikings" from the north.";‬ ‭User Input Strings‬
‭cout << "Type your full name: ";‬
‭The solution to avoid this problem, is to use the backslash escape character.‬ ‭It is possible to use the extraction operator >> on cin to store a string entered by‬
‭getline (cin, fullName);‬
‭The backslash (\) escape character turns special characters into string‬ ‭a user:‬
‭cout << "Your name is: " << fullName;‬
‭characters:‬ ‭Example‬
‭// Type your full name: John Doe‬
‭string firstName;‬
‭// Your name is: John Doe‬
‭Escape character‬ ‭Result‬ ‭Description‬ ‭cout << "Type your first name: ";‬
‭\'‬
‭\"‬
‭'‬
‭"‬
‭Single quote‬
‭Double quote‬
‭cin >> firstName; // get user input from the keyboard‬
‭cout << "Your name is: " << firstName;‬
‭C++ String Namespace‬
‭\\‬ ‭\‬ ‭Backslash‬ ‭// Type your first name: John‬ ‭Omitting Namespace‬
‭The sequence \" inserts a double quote in a string:‬ ‭// Your name is: John‬ ‭You might see some C++ programs that runs without the standard namespace‬
‭Example‬ ‭However, cin considers a space (whitespace, tabs, etc) as a terminating character,‬ ‭library. The using namespace std line can be omitted and replaced with the std‬
‭string txt = "We are the so-called \"Vikings\" from the north.";‬ ‭which means that it can only store a single word (even if you type many words):‬ ‭keyword, followed by the :: operator for string (and cout) objects:‬
‭The sequence \' inserts a single quote in a string:‬ ‭Example‬ ‭Example‬

‭27‬ ‭28‬ ‭29‬

‭#include <iostream>‬ ‭#include <cmath>‬ ‭fmin(x, y)‬ ‭Returns the lowest value of a floating x and y‬
‭#include <string>‬ ‭cout << sqrt(64);‬ ‭fmod(x, y)‬ ‭Returns the floating point remainder of x/y‬
‭int main() {‬ ‭cout << round(2.6);‬ ‭pow(x, y)‬ ‭Returns the value of x to the power of y‬
‭std::string greeting = "Hello";‬ ‭cout << log(2);‬ ‭sin(x)‬ ‭Returns the sine of x (x is in radians)‬
‭std::cout << greeting;‬ ‭Other Math Functions‬ ‭sinh(x)‬ ‭Returns the hyperbolic sine of a double value‬
‭return 0;‬ ‭A list of other popular Math functions (from the <cmath> library) can be found‬ ‭tan(x)‬ ‭Returns the tangent of an angle‬
‭}‬ ‭in the table below:‬ ‭tanh(x)‬ ‭Returns the hyperbolic tangent of a double value‬
‭It is up to you if you want to include the standard namespace library or not.‬
‭C++ Booleans‬
‭C++ Math‬
‭Function‬ ‭Description‬
‭abs(x)‬ ‭Returns the absolute value of x‬
‭C++ Booleans‬
‭acos(x)‬ ‭Returns the arccosine of x‬
‭C++ Math‬ ‭Very often, in programming, you will need a data type that can only have one of‬
‭asin(x)‬ ‭Returns the arcsine of x‬
‭C++ has many functions that allows you to perform mathematical tasks on‬ ‭two values, like:‬
‭atan(x)‬ ‭Returns the arctangent of x‬
‭numbers.‬ ‭YES / NO‬
‭cbrt(x)‬ ‭Returns the cube root of x‬
‭Max and min‬ ‭ON / OFF‬
‭ceil(x)‬ ‭Returns the value of x rounded up to its nearest integer‬
‭The max(x,y) function can be used to find the highest value of x and y:‬ ‭TRUE / FALSE‬
‭cos(x)‬ ‭Returns the cosine of x‬
‭Example‬ ‭For this, C++ has a bool data type, which can take the values true (1) or false (0).‬
‭cosh(x)‬ ‭Returns the hyperbolic cosine of x‬
‭cout << max(5, 10);‬ ‭Boolean Values‬
‭exp(x)‬ ‭Returns the value of Ex‬
‭And the min(x,y) function can be used to find the lowest value of x and y:‬ ‭A boolean variable is declared with the bool keyword and can only take the‬
‭expm1(x)‬ ‭Returns ex -1‬
‭Example‬ ‭values true or false:‬
‭fabs(x)‬ ‭Returns the absolute value of a floating x‬
‭cout << min(5, 10);‬ ‭Example‬
‭fdim(x, y)‬ ‭Returns the positive difference between x and y‬
‭C++ <cmath> Header‬ ‭bool isCodingFun = true;‬
‭floor(x)‬ ‭Returns the value of x rounded down to its nearest integer‬
‭Other functions, such as sqrt (square root), round (rounds a number) and log‬ ‭bool isFishTasty = false;‬
‭hypot(x, y)‬ ‭Returns sqrt(x2 +y2) without intermediate overflow or underflow‬
‭(natural logarithm), can be found in the <cmath> header file:‬ ‭cout << isCodingFun; // Outputs 1 (true)‬
‭fma(x, y, z)‬ ‭Returns x*y+z without losing precision‬
‭Example‬ ‭cout << isFishTasty; // Outputs 0 (false)‬
‭fmax(x, y)‬ ‭Returns the highest value of a floating x and y‬
‭// Include the cmath library‬

‭30‬ ‭31‬ ‭32‬

‭From the example above, you can read that a true value returns 1, and false‬ ‭Real Life Example‬
‭returns 0.‬ ‭Let's think of a "real life example" where we need to find out if a person is old‬ ‭C++ If ... Else‬
‭However, it is more common to return a boolean value by comparing values and‬ ‭enough to vote.‬
‭C++ Conditions and If Statements‬
‭variables .‬ ‭In the example below, we use the >= comparison operator to find out if the age‬
‭You already know that C++ supports the usual logical conditions from‬

‭C++ Boolean Expressions‬


‭(25) is greater than OR equal to the voting age limit, which is set to 18:‬
‭mathematics:‬
‭Example‬
‭Less than: a < b‬
‭int myAge = 25;‬
‭Boolean Expression‬ ‭Less than or equal to: a <= b‬
‭int votingAge = 18;‬
‭A Boolean expression returns a boolean value that is either 1 (true) or 0 (false).‬ ‭Greater than: a > b‬
‭cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are‬
‭This is useful to build logic, and find answers.‬ ‭Greater than or equal to: a >= b‬
‭allowed to vote!‬
‭You can use a comparison operator, such as the greater than (>) operator, to find‬ ‭Equal to a == b‬
‭Cool, right? An even better approach (since we are on a roll now), would be to‬
‭out if an expression (or variable) is true or false:‬ ‭Not Equal to: a != b‬
‭wrap the code above in an if...else statement, so we can perform different‬
‭Example‬ ‭You can use these conditions to perform different actions for different‬
‭actions depending on the result:‬
‭int x = 10;‬ ‭decisions.‬
‭Example‬
‭int y = 9;‬ ‭C++ has the following conditional statements:‬
‭Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise‬
‭cout << (x > y); // returns 1 (true), because 10 is higher than 9‬ ‭Use if to specify a block of code to be executed, if a specified condition is true‬
‭output "Not old enough to vote.":‬
‭Or even easier:‬ ‭Use else to specify a block of code to be executed, if the same condition is false‬
‭int myAge = 25;‬
‭Example‬ ‭Use else if to specify a new condition to test, if the first condition is false‬
‭int votingAge = 18;‬
‭cout << (10 > 9); // returns 1 (true), because 10 is higher than 9‬ ‭Use switch to specify many alternative blocks of code to be executed‬
‭if (myAge >= votingAge) {‬
‭In the examples below, we use the equal to (==) operator to evaluate an‬ ‭The if Statement‬
‭cout << "Old enough to vote!";‬
‭expression:‬ ‭Use the if statement to specify a block of C++ code to be executed if a condition‬
‭} else {‬
‭Example‬ ‭is true.‬
‭cout << "Not old enough to vote.";‬
‭int x = 10;‬ ‭Syntax‬
‭}‬
‭cout << (x == 10); // returns 1 (true), because the value of x is equal to 10‬ ‭if (condition) {‬
‭// Outputs: Old enough to vote!‬
‭Example‬ ‭// block of code to be executed if the condition is true‬
‭Booleans are the basis for all C++ comparisons and conditions.‬
‭cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15‬ ‭}‬

‭33‬ ‭34‬ ‭35‬


‭Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an‬ ‭if (condition) {‬ ‭} else {‬
‭error.‬ ‭// block of code to be executed if the condition is true‬ ‭// block of code to be executed if the condition1 is false and condition2‬
‭} else {‬ ‭is false‬
‭In the example below, we test two values to find out if 20 is greater than 18. If‬ ‭// block of code to be executed if the condition is false‬ ‭}‬
‭the condition is true, print some text:‬ ‭}‬ ‭Example‬
‭Example‬ ‭Example‬ ‭int time = 22;‬
‭if (20 > 18) {‬ ‭int time = 20;‬ ‭if (time < 10) {‬
‭cout << "20 is greater than 18";‬ ‭if (time < 18) {‬ ‭cout << "Good morning.";‬
‭}‬ ‭cout << "Good day.";‬ ‭} else if (time < 20) {‬
‭We can also test variables:‬ ‭} else {‬ ‭cout << "Good day.";‬
‭Example‬ ‭cout << "Good evening.";‬ ‭} else {‬
‭int x = 20;‬ ‭}‬ ‭cout << "Good evening.";‬
‭int y = 18;‬ ‭// Outputs "Good evening."‬ ‭}‬
‭if (x > y) {‬ ‭Example explained‬ ‭// Outputs "Good evening."‬
‭cout << "x is greater than y";‬ ‭In the example above, time (20) is greater than 18, so the condition is false.‬ ‭Example explained‬
‭}‬ ‭Because of this, we move on to the else condition and print to the screen "Good‬ ‭In the example above, time (22) is greater than 10, so the first condition is false.‬
‭Example explained‬ ‭evening". If the time was less than 18, the program would print "Good day".‬ ‭The next condition, in the else if statement, is also false, so we move on to the‬
‭In the example above we use two variables, x and y, to test whether x is greater‬ ‭The else if Statement‬ ‭else condition since condition1 and condition2 is both false - and print to the‬
‭than y (using the > operator). As x is 20, and y is 18, and we know that 20 is‬ ‭Use the else if statement to specify a new condition if the first condition is false.‬ ‭screen "Good evening".‬
‭greater than 18, we print to the screen that "x is greater than y".‬ ‭Syntax‬ ‭However, if the time was 14, our program would print "Good day."‬
‭The else Statement‬ ‭if (condition1) {‬
‭Use the else statement to specify a block of code to be executed if the condition‬ ‭// block of code to be executed if condition1 is true‬
‭C++ Short Hand If Else‬
‭is false.‬ ‭} else if (condition2) {‬ ‭Short Hand If...Else (Ternary Operator)‬

‭// block of code to be executed if the condition1 is false and condition2‬


‭Syntax‬ ‭is true‬

‭36‬ ‭37‬ ‭38‬

‭There is also a short-hand if else, which is known as the ternary operator‬ ‭// code block‬ ‭cout << "Wednesday";‬
‭because it consists of three operands. It can be used to replace multiple lines of‬ ‭break;‬ ‭break;‬
‭code with a single line. It is often used to replace simple if else statements:‬ ‭case y:‬ ‭case 4:‬
‭Syntax‬ ‭// code block‬ ‭cout << "Thursday";‬
‭variable = (condition) ? expressionTrue : expressionFalse;‬ ‭break;‬ ‭break;‬
‭Instead of writing:‬ ‭default:‬ ‭case 5:‬
‭Example‬ ‭// code block‬ ‭cout << "Friday";‬
‭int time = 20;‬ ‭}‬ ‭break;‬
‭if (time < 18) {‬ ‭This is how it works:‬ ‭case 6:‬
‭cout << "Good day.";‬ ‭The switch expression is evaluated once‬ ‭cout << "Saturday";‬
‭} else {‬ ‭The value of the expression is compared with the values of each case‬ ‭break;‬
‭cout << "Good evening.";‬ ‭If there is a match, the associated block of code is executed‬ ‭case 7:‬
‭}‬ ‭The break and default keywords are optional, and will be described later in this‬ ‭cout << "Sunday";‬
‭You can simply write:‬ ‭chapter‬ ‭break;‬
‭Example‬ ‭The example below uses the weekday number to calculate the weekday name:‬ ‭}‬
‭int time = 20;‬ ‭Example‬ ‭// Outputs "Thursday" (day 4)‬
‭string result = (time < 18) ? "Good day." : "Good evening.";‬ ‭int day = 4;‬ ‭The break Keyword‬
‭cout << result;‬ ‭switch (day) {‬ ‭When C++ reaches a break keyword, it breaks out of the switch block.‬

‭C++ Switch‬
‭case 1:‬ ‭This will stop the execution of more code and case testing inside the block.‬
‭cout << "Monday";‬ ‭When a match is found, and the job is done, it's time for a break. There is no‬
‭break;‬ ‭need for more testing.‬
‭C++ Switch Statements‬
‭case 2:‬ ‭A break can save a lot of execution time because it "ignores" the execution of all‬
‭Use the switch statement to select one of many code blocks to be executed.‬
‭cout << "Tuesday";‬ ‭the rest of the code in the switch block.‬
‭Syntax‬
‭break;‬
‭switch(expression) {‬
‭case 3:‬ ‭The default Keyword‬
‭case x:‬

‭39‬ ‭40‬ ‭41‬

‭The default keyword specifies some code to run if there is no case match:‬ ‭// code block to be executed‬ ‭The example below uses a do/while loop. The loop will always be executed at‬
‭Example‬ ‭}‬ ‭least once, even if the condition is false, because the code block is executed‬
‭int day = 4;‬ ‭In the example below, the code in the loop will run, over and over again, as long‬ ‭before the condition is tested:‬
‭switch (day) {‬ ‭as a variable (i) is less than 5:‬ ‭Example‬
‭case 6:‬ ‭Example‬ ‭int i = 0;‬
‭cout << "Today is Saturday";‬ ‭int i = 0;‬ ‭do {‬
‭break;‬ ‭while (i < 5) {‬ ‭cout << i << "\n";‬
‭case 7:‬ ‭cout << i << "\n";‬ ‭i++;‬
‭cout << "Today is Sunday";‬ ‭i++;‬ ‭}‬
‭break;‬ ‭}‬ ‭while (i < 5);‬
‭default:‬ ‭Note: Do not forget to increase the variable used in the condition, otherwise the‬ ‭Do not forget to increase the variable used in the condition, otherwise the loop‬
‭cout << "Looking forward to the Weekend";‬ ‭loop will never end!‬ ‭will never end!‬
‭}‬
‭// Outputs "Looking forward to the Weekend"‬ ‭C++ Do/While Loop‬ ‭C++ For Loop‬
‭C++ While Loop‬ ‭The Do/While Loop‬
‭The do/while loop is a variant of the while loop. This loop will execute the code‬
‭C++ For Loop‬
‭When you know exactly how many times you want to loop through a block of‬
‭C++ Loops‬ ‭block once, before checking if the condition is true, then it will repeat the loop‬ ‭code, use the for loop instead of a while loop:‬
‭Loops can execute a block of code as long as a specified condition is reached.‬ ‭as long as the condition is true.‬ ‭Syntax‬
‭Loops are handy because they save time, reduce errors, and they make code‬ ‭Syntax‬ ‭for (statement 1; statement 2; statement 3) {‬
‭more readable.‬ ‭do {‬ ‭// code block to be executed‬
‭C++ While Loop‬ ‭// code block to be executed‬ ‭}‬
‭The while loop loops through a block of code as long as a specified condition is‬ ‭}‬ ‭Statement 1 is executed (one time) before the execution of the code block.‬
‭true:‬ ‭while (condition);‬ ‭Statement 2 defines the condition for executing the code block.‬
‭Syntax‬ ‭Statement 3 is executed (every time) after the code block has been executed.‬
‭while (condition) {‬

‭42‬ ‭43‬ ‭44‬


‭The example below will print the numbers 0 to 4:‬ ‭// Outer loop‬ ‭You have already seen the break statement used in an earlier chapter of this‬
‭Example‬ ‭for (int i = 1; i <= 2; ++i) {‬ ‭tutorial. It was used to "jump out" of a switch statement.‬
‭for (int i = 0; i < 5; i++) {‬ ‭cout << "Outer: " << i << "\n"; // Executes 2 times‬ ‭The break statement can also be used to jump out of a loop.‬
‭cout << i << "\n";‬ ‭// Inner loop‬ ‭This example jumps out of the loop when i is equal to 4:‬
‭}‬ ‭for (int j = 1; j <= 3; ++j) {‬ ‭Example‬
‭Example explained‬ ‭cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)‬ ‭for (int i = 0; i < 10; i++) {‬
‭Statement 1 sets a variable before the loop starts (int i = 0).‬ ‭}‬ ‭if (i == 4) {‬
‭Statement 2 defines the condition for the loop to run (i must be less than 5). If‬ ‭}‬ ‭break;‬
‭the condition is true, the loop will start over again, if it is false, the loop will‬ ‭The foreach Loop‬ ‭}‬
‭end.‬ ‭There is also a "for-each loop" (introduced in C++ version 11 (2011), which is‬ ‭cout << i << "\n";‬
‭Statement 3 increases a value (i++) each time the code block in the loop has been‬ ‭used exclusively to loop through elements in an array (or other data sets):‬ ‭}‬
‭executed.‬ ‭Syntax‬ ‭C++ Continue‬
‭for (type variableName : arrayName) {‬ ‭The continue statement breaks one iteration (in the loop), if a specified‬
‭Another Example‬ ‭// code block to be executed‬ ‭condition occurs, and continues with the next iteration in the loop.‬
‭This example will only print even values between 0 and 10:‬ ‭}‬ ‭This example skips the value of 4:‬
‭Example‬ ‭The following example outputs all elements in an array, using a "for-each loop":‬ ‭Example‬
‭for (int i = 0; i <= 10; i = i + 2) {‬ ‭Example‬ ‭for (int i = 0; i < 10; i++) {‬
‭cout << i << "\n";‬ ‭int myNumbers[5] = {10, 20, 30, 40, 50};‬ ‭if (i == 4) {‬
‭}‬ ‭for (int i : myNumbers) {‬ ‭continue;‬
‭Nested Loops‬ ‭cout << i << "\n";‬ ‭}‬
‭It is also possible to place a loop inside another loop. This is called a nested‬ ‭}‬ ‭cout << i << "\n";‬
‭loop.‬
‭C++ Break and Continue‬
‭}‬
‭The "inner loop" will be executed one time for each iteration of the "outer‬ ‭Break and Continue in While Loop‬
‭loop":‬ ‭You can also use break and continue in while loops:‬
‭C++ Break‬
‭Example‬ ‭Break Example‬

‭45‬ ‭46‬ ‭47‬

‭int i = 0;‬ ‭string cars[4];‬ ‭// Now outputs Opel instead of Volvo‬
‭while (i < 10) {‬ ‭We have now declared a variable that holds an array of four strings. To insert‬
‭cout << i << "\n";‬ ‭values to it, we can use an array literal - place the values in a comma-separated‬ ‭C++ Arrays and Loops‬
‭i++;‬ ‭list, inside curly braces:‬
‭Loop Through an Array‬
‭if (i == 4) {‬ ‭string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};‬
‭You can loop through the array elements with the for loop.‬
‭break;‬ ‭To create an array of three integers, you could write:‬
‭The following example outputs all elements in the cars array:‬
‭}‬ ‭int myNum[3] = {10, 20, 30};‬
‭Example‬
‭}‬ ‭Access the Elements of an Array‬
‭string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};‬
‭Continue Example‬ ‭You access an array element by referring to the index number inside square‬
‭for (int i = 0; i < 5; i++) {‬
‭int i = 0;‬ ‭brackets [].‬
‭cout << cars[i] << "\n";‬
‭while (i < 10) {‬ ‭This statement accesses the value of the first element in cars:‬
‭}‬
‭if (i == 4) {‬ ‭Example‬
‭This example outputs the index of each element together with its value:‬
‭i++;‬ ‭string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};‬
‭Example‬
‭continue;‬ ‭cout << cars[0];‬
‭string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};‬
‭}‬ ‭// Outputs Volvo‬
‭for (int i = 0; i < 5; i++) {‬
‭cout << i << "\n";‬ ‭Note: Array indexes start with 0: [0] is the first element. [1] is the second‬
‭cout << i << " = " << cars[i] << "\n";‬
‭i++;‬ ‭element, etc.‬
‭}‬
‭}‬
‭And this example shows how to loop through an array of integers:‬

‭C++ Arrays‬
‭Change an Array Element‬
‭Example‬
‭To change the value of a specific element, refer to the index number:‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭cars[0] = "Opel";‬
‭C++ Arrays‬ ‭for (int i = 0; i < 5; i++) {‬
‭Example‬
‭Arrays are used to store multiple values in a single variable, instead of declaring‬ ‭cout << myNumbers[i] << "\n";‬
‭string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};‬
‭separate variables for each value.‬ ‭}‬
‭cars[0] = "Opel";‬
‭To declare an array, define the variable type, specify the name of the array‬ ‭The foreach Loop‬
‭cout << cars[0];‬
‭followed by square brackets and specify the number of elements it should store:‬

‭48‬ ‭49‬ ‭50‬

‭There is also a "for-each loop" (introduced in C++ version 11 (2011), which is‬ ‭It is also possible to declare an array without specifying the elements on‬ ‭Loop Through an Array with sizeof()‬
‭used exclusively to loop through elements in an array:‬ ‭declaration, and add them later:‬ ‭In the Arrays and Loops Chapter, we wrote the size of the array in the loop‬
‭Syntax‬ ‭Example‬ ‭condition (i < 5). This is not ideal, since it will only work for arrays of a specified‬
‭for (type variableName : arrayName) {‬ ‭string cars[5];‬ ‭size.‬
‭// code block to be executed‬ ‭cars[0] = "Volvo";‬ ‭However, by using the sizeof() approach from the example above, we can now‬
‭}‬ ‭cars[1] = "BMW";‬ ‭make loops that work for arrays of any size, which is more sustainable.‬
‭The following example outputs all elements in an array, using a "for-each loop":‬
‭C++ Array Size‬
‭Instead of writing:‬
‭Example‬ ‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬ ‭for (int i = 0; i < 5; i++) {‬
‭Get the Size of an Array‬
‭for (int i : myNumbers) {‬ ‭cout << myNumbers[i] << "\n";‬
‭To get the size of an array, you can use the sizeof() operator:‬
‭cout << i << "\n";‬ ‭}‬
‭Example‬
‭}‬ ‭It is better to write:‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬

‭C++ Omit Array Size‬


‭Example‬
‭cout << sizeof(myNumbers);‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭Result: 20‬
‭for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {‬
‭Omit Array Size‬ ‭Why did the result show 20 instead of 5, when the array contains 5 elements?‬
‭cout << myNumbers[i] << "\n";‬
‭In C++, you don't have to specify the size of the array. The compiler is smart‬ ‭It is because the sizeof() operator returns the size of a type in bytes.‬
‭}‬
‭enough to determine the size of the array based on the number of inserted‬ ‭You learned from the Data Types chapter that an int type is usually 4 bytes, so‬
‭Note that, in C++ version 11 (2011), you can also use the "for-each" loop:‬
‭values:‬ ‭from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.‬
‭Example‬
‭string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements‬ ‭To find out how many elements an array has, you have to divide the size of the‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭The example above is equal to:‬ ‭array by the size of the data type it contains:‬
‭for (int i : myNumbers) {‬
‭string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements‬ ‭Example‬
‭cout << i << "\n";‬
‭However, the last approach is considered as "good practice", because it will‬ ‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭}‬
‭reduce the chance of errors in your program.‬ ‭int getArrayLength = sizeof(myNumbers) / sizeof(int);‬
‭It is good to know the different ways to loop through an array, since you may‬
‭Omit Elements on Declaration‬ ‭cout << getArrayLength;‬
‭encounter them all in different programs.‬
‭Result: 5‬

‭51‬ ‭52‬ ‭53‬


‭C++ Multi-Dimensional Arrays‬
‭{‬ ‭{ "E", "F", "G", "H" }‬
‭{ "E", "F" },‬ ‭};‬
‭{ "G", "H" }‬ ‭letters[0][0] = "Z";‬
‭Multi-Dimensional Arrays‬
‭}‬ ‭cout << letters[0][0]; // Now outputs "Z" instead of "A"‬
‭A multi-dimensional array is an array of arrays.‬
‭};‬ ‭Loop Through a Multi-Dimensional Array‬
‭To declare a multi-dimensional array, define the variable type, specify the name‬
‭Access the Elements of a Multi-Dimensional Array‬ ‭To loop through a multi-dimensional array, you need one loop for each of the‬
‭of the array followed by square brackets which specify how many elements the‬
‭To access an element of a multi-dimensional array, specify an index number in‬ ‭array's dimensions.‬
‭main array has, followed by another set of square brackets which indicates how‬
‭each of the array's dimensions.‬ ‭The following example outputs all elements in the letters array:‬
‭many elements the sub-arrays have:‬
‭This statement accesses the value of the element in the first row (0) and third‬ ‭Example‬
‭string letters[2][4];‬
‭column (2) of the letters array.‬ ‭string letters[2][4] = {‬
‭As with ordinary arrays, you can insert values with an array literal - a‬
‭Example‬ ‭{ "A", "B", "C", "D" },‬
‭comma-separated list inside curly braces. In a multi-dimensional array, each‬
‭string letters[2][4] = {‬ ‭{ "E", "F", "G", "H" }‬
‭element in an array literal is another array literal.‬
‭{ "A", "B", "C", "D" },‬ ‭};‬
‭string letters[2][4] = {‬
‭{ "E", "F", "G", "H" }‬ ‭for (int i = 0; i < 2; i++) {‬
‭{ "A", "B", "C", "D" },‬
‭};‬ ‭for (int j = 0; j < 4; j++) {‬
‭{ "E", "F", "G", "H" }‬
‭cout << letters[0][2]; // Outputs "C"‬ ‭cout << letters[i][j] << "\n";‬
‭};‬
‭Remember that: Array indexes start with 0: [0] is the first element. [1] is the‬ ‭}‬
‭Each set of square brackets in an array declaration adds another dimension to‬
‭second element, etc.‬ ‭}‬
‭an array. An array like the one above is said to have two dimensions.‬
‭This example shows how to loop through a three-dimensional array:‬
‭Arrays can have any number of dimensions. The more dimensions an array has,‬
‭Change Elements in a Multi-Dimensional Array‬ ‭Example‬
‭the more complex the code becomes. The following array has three dimensions:‬
‭To change the value of an element, refer to the index number of the element in‬ ‭string letters[2][2][2] = {‬
‭string letters[2][2][2] = {‬
‭each of the dimensions:‬ ‭{‬
‭{‬
‭Example‬ ‭{ "A", "B" },‬
‭{ "A", "B" },‬
‭string letters[2][4] = {‬ ‭{ "C", "D" }‬
‭{ "C", "D" }‬
‭{ "A", "B", "C", "D" },‬ ‭},‬
‭},‬

‭54‬ ‭55‬ ‭56‬

‭{‬ ‭// Keep track of how many hits the player has and how many turns they‬ ‭}‬
‭{ "E", "F" },‬ ‭have played in these variables‬ ‭// Count how many turns the player has taken‬
‭{ "G", "H" }‬ ‭int hits = 0;‬ ‭numberOfTurns++;‬
‭}‬ ‭int numberOfTurns = 0;‬ ‭}‬
‭};‬ ‭// Allow the player to keep going until they have hit all four ships‬ ‭cout << "Victory!\n";‬
‭for (int i = 0; i < 2; i++) {‬ ‭while (hits < 4) {‬ ‭cout << "You won in " << numberOfTurns << " turns";‬
‭for (int j = 0; j < 2; j++) {‬ ‭int row, column;‬
‭for (int k = 0; k < 2; k++) {‬ ‭cout << "Selecting coordinates\n";‬ ‭C++ Structures (struct)‬
‭cout << letters[i][j][k] << "\n";‬ ‭// Ask the player for a row‬
‭C++ Structures‬
‭}‬ ‭cout << "Choose a row number between 0 and 3: ";‬
‭Structures (also called structs) are a way to group several related variables into‬
‭}‬ ‭cin >> row;‬
‭one place. Each variable in the structure is known as a member of the structure.‬
‭}‬ ‭// Ask the player for a column‬
‭Unlike an array, a structure can contain many different data types (int, string,‬
‭Why Multi-Dimensional Arrays?‬ ‭cout << "Choose a column number between 0 and 3: ";‬
‭bool, etc.).‬
‭Multi-dimensional arrays are great at representing grids. This example shows a‬ ‭cin >> column;‬
‭Create a Structure‬
‭practical use for them. In the following example we use a multi-dimensional‬ ‭// Check if a ship exists in those coordinates‬
‭To create a structure, use the struct keyword and declare each of its members‬
‭array to represent a small game of Battleship:‬ ‭if (ships[row][column]) {‬
‭inside curly braces.‬
‭Example‬ ‭// If the player hit a ship, remove it by setting the value to zero.‬
‭After the declaration, specify the name of the structure variable (myStructure in‬
‭// We put "1" to indicate there is a ship.‬ ‭ships[row][column] = 0;‬
‭the example below):‬
‭bool ships[4][4] = {‬ ‭// Increase the hit counter‬
‭struct { // Structure declaration‬
‭{ 0, 1, 1, 0 },‬ ‭hits++;‬
‭int myNum; // Member (int variable)‬
‭{ 0, 0, 0, 0 },‬ ‭// Tell the player that they have hit a ship and how many ships are left‬
‭string myString; // Member (string variable)‬
‭{ 0, 0, 1, 0 },‬ ‭cout << "Hit! " << (4-hits) << " left.\n\n";‬
‭} myStructure; // Structure variable‬
‭{ 0, 0, 1, 0 }‬ ‭} else {‬
‭Access Structure Members‬
‭};‬ ‭// Tell the player that they missed‬
‭To access members of a structure, use the dot syntax (.):‬
‭cout << "Miss\n\n";‬
‭Example‬

‭57‬ ‭58‬ ‭59‬

‭Assign data to members of a structure and print it:‬ ‭string model;‬ ‭string myString;‬
‭// Create a structure variable called myStructure‬ ‭int year;‬ ‭};‬
‭struct {‬ ‭} myCar1, myCar2; // We can add variables by separating them with a‬ ‭To declare a variable that uses the structure, use the name of the structure as the‬
‭int myNum;‬ ‭comma here‬ ‭data type of the variable:‬
‭string myString;‬ ‭// Put data into the first structure‬ ‭myDataType myVar;‬
‭} myStructure;‬ ‭myCar1.brand = "BMW";‬ ‭Example‬
‭// Assign values to members of myStructure‬ ‭myCar1.model = "X5";‬ ‭Use one structure to represent two cars:‬
‭myStructure.myNum = 1;‬ ‭myCar1.year = 1999;‬ ‭// Declare a structure named "car"‬
‭myStructure.myString = "Hello World!";‬ ‭// Put data into the second structure‬ ‭struct car {‬
‭// Print members of myStructure‬ ‭myCar2.brand = "Ford";‬ ‭string brand;‬
‭cout << myStructure.myNum << "\n";‬ ‭myCar2.model = "Mustang";‬ ‭string model;‬
‭cout << myStructure.myString << "\n";‬ ‭myCar2.year = 1969;‬ ‭int year;‬
‭One Structure in Multiple Variables‬ ‭// Print the structure members‬ ‭};‬
‭You can use a comma (,) to use one structure in many variables:‬ ‭cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year <<‬ ‭int main() {‬
‭struct {‬ ‭"\n";‬ ‭// Create a car structure and store it in myCar1;‬
‭int myNum;‬ ‭cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<‬ ‭car myCar1;‬
‭string myString;‬ ‭"\n";‬ ‭myCar1.brand = "BMW";‬
‭} myStruct1, myStruct2, myStruct3; // Multiple structure variables‬ ‭Named Structures‬ ‭myCar1.model = "X5";‬
‭separated with‬ ‭By giving a name to the structure, you can treat it as a data type. This means‬ ‭myCar1.year = 1999;‬
‭commas‬ ‭that you can create variables with this structure anywhere in the program at any‬
‭This example shows how to use a structure in two different variables:‬ ‭time.‬ ‭// Create another car structure and store it in myCar2;‬
‭Example‬ ‭To create a named structure, put the name of the structure right after the struct‬ ‭car myCar2;‬
‭Use one structure to represent two cars:‬ ‭keyword:‬ ‭myCar2.brand = "Ford";‬
‭struct {‬ ‭struct myDataType { // This structure is named "myDataType"‬ ‭myCar2.model = "Mustang";‬
‭string brand;‬ ‭int myNum;‬ ‭myCar2.year = 1969;‬

‭60‬ ‭61‬ ‭62‬


‭// Print the structure members‬ ‭Memory Address‬ ‭string food = "Pizza"; // A food variable of type string‬
‭cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year <<‬ ‭In the example from the previous page, the & operator was used to create a‬ ‭cout << food; // Outputs the value of food (Pizza)‬
‭"\n";‬ ‭reference variable. But it can also be used to get the memory address of a‬ ‭cout << &food; // Outputs the memory address of food (0x6dfed4)‬
‭cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<‬ ‭variable; which is the location of where the variable is stored on the computer.‬ ‭A pointer however, is a variable that stores the memory address as its value.‬
‭"\n";‬ ‭When a variable is created in C++, a memory address is assigned to the variable.‬ ‭A pointer variable points to a data type (like int or string) of the same type, and‬
‭return 0;‬ ‭And when we assign a value to the variable, it is stored in this memory address.‬ ‭is created with the * operator. The address of the variable you're working with is‬
‭}‬ ‭To access it, use the & operator, and the result will represent where the variable‬ ‭assigned to the pointer:‬

‭C++ References‬
‭is stored:‬ ‭Example‬
‭Example‬ ‭string food = "Pizza"; // A food variable of type string‬
‭string food = "Pizza";‬ ‭string* ptr = &food; // A pointer variable, with the name ptr, that stores‬
‭Creating References‬
‭cout << &food; // Outputs 0x6dfed4‬ ‭the address of food‬
‭A reference variable is a "reference" to an existing variable, and it is created‬
‭Note: The memory address is in hexadecimal form (0x..). Note that you may not‬ ‭// Output the value of food (Pizza)‬
‭with the & operator:‬
‭get the same result in your program.‬ ‭cout << food << "\n";‬
‭string food = "Pizza"; // food variable‬
‭And why is it useful to know the memory address?‬ ‭// Output the memory address of food (0x6dfed4)‬
‭string &meal = food; // reference to food‬
‭References and Pointers (which you will learn about in the next chapter) are‬ ‭cout << &food << "\n";‬
‭Now, we can use either the variable name food or the reference name meal to‬
‭important in C++, because they give you the ability to manipulate the data in the‬ ‭// Output the memory address of food with the pointer (0x6dfed4)‬
‭refer to the food variable:‬
‭computer's memory - which can reduce the code and improve the performance.‬ ‭cout << ptr << "\n";‬
‭Example‬
‭These two features are one of the things that make C++ stand out from other‬ ‭Example explained‬
‭string food = "Pizza";‬
‭programming languages, like Python and Java.‬ ‭Create a pointer variable with the name ptr, that points to a string variable, by‬
‭string &meal = food;‬

‭C++ Pointers‬
‭using the asterisk sign * (string* ptr). Note that the type of the pointer has to‬
‭cout << food << "\n"; // Outputs Pizza‬
‭match the type of the variable you're working with.‬
‭cout << meal << "\n"; // Outputs Pizza‬
‭Use the & operator to store the memory address of the variable called food, and‬
‭Creating Pointers‬
‭assign it to the pointer.‬
‭You learned from the previous chapter, that we can get the memory address of a‬
‭Now, ptr holds the value of food's memory address.‬

‭C++ Memory Address‬


‭variable by using the & operator:‬
‭Example‬

‭63‬ ‭64‬ ‭65‬

‭Tip: There are three ways to declare pointer variables, but the first way is‬
‭C++ Modify Pointers‬
‭Functions are used to perform certain actions, and they are important for‬
‭preferred:‬ ‭reusing code: Define the code once, and use it many times.‬
‭Create a Function‬
‭Modify the Pointer Value‬
‭string* mystring; // Preferred‬ ‭C++ provides some pre-defined functions, such as main(), which is used to‬
‭You can also change the pointer's value. But note that this will also change the‬
‭string *mystring;‬ ‭execute code. But you can also create your own functions to perform certain‬
‭value of the original variable:‬
‭string * mystring;‬ ‭actions.‬
‭Example‬

‭C++ Dereference‬
‭To create (often referred to as declare) a function, specify the name of the‬
‭string food = "Pizza";‬
‭function, followed by parentheses ():‬
‭string* ptr = &food;‬
‭Syntax‬
‭Get Memory Address and Value‬ ‭// Output the value of food (Pizza)‬
‭void myFunction() {‬
‭In the example from the previous page, we used the pointer variable to get the‬ ‭cout << food << "\n";‬
‭// code to be executed‬
‭memory address of a variable (used together with the & reference operator).‬ ‭// Output the memory address of food (0x6dfed4)‬
‭}‬
‭However, you can also use the pointer to get the value of the variable, by using‬ ‭cout << &food << "\n";‬
‭Example Explained‬
‭the * operator (the dereference operator):‬ ‭// Access the memory address of food and output its value (Pizza)‬
‭myFunction() is the name of the function‬
‭Example‬ ‭cout << *ptr << "\n";‬
‭void means that the function does not have a return value. You will learn more‬
‭string food = "Pizza"; // Variable declaration‬ ‭// Change the value of the pointer‬
‭about return values later in the next chapter‬
‭string* ptr = &food; // Pointer declaration‬ ‭*ptr = "Hamburger";‬
‭inside the function (the body), add code that defines what the function should do‬
‭// Reference: Output the memory address of food with the pointer‬ ‭// Output the new value of the pointer (Hamburger)‬
‭Call a Function‬
‭(0x6dfed4)‬ ‭cout << *ptr << "\n";‬
‭Declared functions are not executed immediately. They are "saved for later use",‬
‭cout << ptr << "\n";‬ ‭// Output the new value of the food variable (Hamburger)‬
‭and will be executed later, when they are called.‬
‭// Dereference: Output the value of food with the pointer (Pizza)‬ ‭cout << food << "\n";‬
‭To call a function, write the function's name followed by two parentheses () and‬
‭cout << *ptr << "\n";‬
‭Note that the * sign can be confusing here, as it does two different things in our‬ ‭C++ Functions‬ ‭a semicolon ;‬
‭In the following example, myFunction() is used to print a text (the action), when‬
‭code:‬
‭A function is a block of code which only runs when it is called.‬ ‭it is called:‬
‭When used in declaration (string* ptr), it creates a pointer variable.‬
‭You can pass data, known as parameters, into a function.‬ ‭Example‬
‭When not used in declaration, it act as a dereference operator.‬

‭66‬ ‭67‬ ‭68‬

‭Inside main, call myFunction():‬ ‭A C++ function consist of two parts:‬


‭// Create a function‬ ‭Declaration: the return type, the name of the function, and parameters (if any)‬ ‭// The main method‬
‭void myFunction() {‬ ‭Definition: the body of the function (code to be executed)‬ ‭int main() {‬
‭cout << "I just got executed!";‬ ‭void myFunction() { // declaration‬ ‭myFunction(); // call the function‬
‭}‬ ‭// the body of the function (definition)‬ ‭return 0;‬
‭int main() {‬ ‭}‬ ‭}‬
‭myFunction(); // call the function‬ ‭Note: If a user-defined function, such as myFunction() is declared after the‬
‭return 0;‬ ‭main() function, an error will occur:‬ ‭// Function definition‬
‭}‬ ‭Example‬ ‭void myFunction() {‬
‭// Outputs "I just got executed!"‬ ‭int main() {‬ ‭cout << "I just got executed!";‬
‭A function can be called multiple times:‬ ‭myFunction();‬ ‭}‬
‭Example‬ ‭return 0;‬
‭void myFunction() {‬ ‭}‬ ‭C++ Function Parameters‬
‭cout << "I just got executed!\n";‬ ‭void myFunction() {‬
‭Parameters and Arguments‬
‭}‬ ‭cout << "I just got executed!";‬
‭Information can be passed to functions as a parameter. Parameters act as‬
‭int main() {‬ ‭}‬
‭variables inside the function.‬
‭myFunction();‬ ‭// Error‬
‭Parameters are specified after the function name, inside the parentheses. You‬
‭myFunction();‬ ‭However, it is possible to separate the declaration and the definition of the‬
‭can add as many parameters as you want, just separate them with a comma:‬
‭myFunction();‬ ‭function - for code optimization.‬
‭Syntax‬
‭return 0;‬ ‭You will often see C++ programs that have function declaration above main(),‬
‭void functionName(parameter1, parameter2, parameter3) {‬
‭}‬ ‭and function definition below main(). This will make the code better organized‬
‭// code to be executed‬
‭// I just got executed!‬ ‭and easier to read:‬
‭}‬
‭// I just got executed!‬ ‭Example‬
‭The following example has a function that takes a string called fname as‬
‭// I just got executed!‬ ‭// Function declaration‬
‭parameter. When the function is called, we pass along a first name, which is‬
‭Function Declaration and Definition‬ ‭void myFunction();‬
‭used inside the function to print the full name:‬

‭69‬ ‭70‬ ‭71‬


‭Example‬ ‭int main() {‬ ‭myFunction("Anja", 30);‬
‭void myFunction(string fname) {‬ ‭myFunction("Sweden");‬ ‭return 0;‬
‭cout << fname << " Refsnes\n";‬ ‭myFunction("India");‬ ‭}‬
‭}‬ ‭myFunction();‬ ‭// Liam Refsnes. 3 years old.‬
‭int main() {‬ ‭myFunction("USA");‬ ‭// Jenny Refsnes. 14 years old.‬
‭myFunction("Liam");‬ ‭return 0;‬ ‭// Anja Refsnes. 30 years old.‬
‭myFunction("Jenny");‬ ‭}‬ ‭Note that when you are working with multiple parameters, the function call‬
‭myFunction("Anja");‬ ‭// Sweden‬ ‭must have the same number of arguments as there are parameters, and the‬
‭return 0;‬ ‭// India‬ ‭arguments must be passed in the same order.‬
‭}‬ ‭// Norway‬
‭// Liam Refsnes‬ ‭// USA‬
‭// Jenny Refsnes‬ ‭A parameter with a default value, is often known as an "optional parameter".‬ ‭C++ The Return Keyword‬
‭// Anja Refsnes‬ ‭From the example above, country is an optional parameter and "Norway" is the‬
‭Return Values‬
‭When a parameter is passed to the function, it is called an argument. So, from‬ ‭default value.‬
‭The void keyword, used in the previous examples, indicates that the function‬
‭the example above: fname is a parameter, while Liam, Jenny and Anja are‬
‭arguments.‬ ‭C++ Multiple Parameters‬ ‭should not return a value. If you want the function to return a value, you can use‬
‭a data type (such as int, string, etc.) instead of void, and use the return keyword‬

‭C++ Default Parameters‬ ‭Multiple Parameters‬


‭Inside the function, you can add as many parameters as you want:‬
‭inside the function:‬
‭Example‬
‭Default Parameter Value‬ ‭Example‬ ‭int myFunction(int x) {‬
‭You can also use a default parameter value, by using the equals sign (=).‬ ‭void myFunction(string fname, int age) {‬ ‭return 5 + x;‬
‭If we call the function without an argument, it uses the default value ("Norway"):‬ ‭cout << fname << " Refsnes. " << age << " years old. \n";‬ ‭}‬
‭Example‬ ‭}‬ ‭int main() {‬
‭void myFunction(string country = "Norway") {‬ ‭int main() {‬ ‭cout << myFunction(3);‬
‭cout << country << "\n";‬ ‭myFunction("Liam", 3);‬ ‭return 0;‬
‭}‬ ‭myFunction("Jenny", 14);‬ ‭}‬

‭72‬ ‭73‬ ‭74‬

‭// Outputs 8 (5 + 3)‬ ‭Pass By Reference‬ ‭Pass Arrays as Function Parameters‬


‭This example returns the sum of a function with two parameters:‬ ‭In the examples from the previous page, we used normal variables when we‬ ‭You can also pass arrays to a function:‬
‭Example‬ ‭passed parameters to a function. You can also pass a reference to the function.‬ ‭Example‬
‭int myFunction(int x, int y) {‬ ‭This can be useful when you need to change the value of the arguments:‬ ‭void myFunction(int myNumbers[5]) {‬
‭return x + y;‬ ‭Example‬ ‭for (int i = 0; i < 5; i++) {‬
‭}‬ ‭void swapNums(int &x, int &y) {‬ ‭cout << myNumbers[i] << "\n";‬
‭int main() {‬ ‭int z = x;‬ ‭}‬
‭cout << myFunction(5, 3);‬ ‭x = y;‬ ‭}‬
‭return 0;‬ ‭y = z;‬ ‭int main() {‬
‭}‬ ‭}‬ ‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭// Outputs 8 (5 + 3)‬ ‭int main() {‬ ‭myFunction(myNumbers);‬
‭You can also store the result in a variable:‬ ‭int firstNum = 10;‬ ‭return 0;‬
‭Example‬ ‭int secondNum = 20;‬ ‭}‬
‭int myFunction(int x, int y) {‬ ‭cout << "Before swap: " << "\n";‬ ‭Example Explained‬
‭return x + y;‬ ‭cout << firstNum << secondNum << "\n";‬ ‭The function (myFunction) takes an array as its parameter (int myNumbers[5]),‬
‭}‬ ‭// Call the function, which will change the values of firstNum and‬ ‭and loops through the array elements with the for loop.‬
‭int main() {‬ ‭secondNum‬
‭int z = myFunction(5, 3);‬ ‭swapNums(firstNum, secondNum);‬ ‭When the function is called inside main(), we pass along the myNumbers array,‬
‭cout << z;‬ ‭cout << "After swap: " << "\n";‬ ‭which outputs the array elements.‬
‭return 0;‬ ‭cout << firstNum << secondNum << "\n";‬
‭}‬ ‭return 0;‬ ‭Note that when you call the function, you only need to use the name of the array‬
‭// Outputs 8 (5 + 3)‬ ‭}‬ ‭when passing it as an argument myFunction(myNumbers). However, the full‬
‭declaration of the array is needed in the function parameter (int myNumbers[5]).‬

‭C++ Functions - Pass By Reference‬ ‭C++ Pass Array to a Function‬


‭75‬ ‭76‬ ‭77‬

‭C++ Function Overloading‬


‭Instead of defining two functions that should do the same thing, it is better to‬ ‭Recursion is the technique of making a function call itself. This technique‬
‭overload one.‬ ‭provides a way to break complicated problems down into simple problems‬
‭In the example below, we overload the plusFunc function to work for both int‬ ‭which are easier to solve.‬
‭Function Overloading‬
‭and double:‬ ‭Recursion may be a bit difficult to understand. The best way to figure out how it‬
‭With function overloading, multiple functions can have the same name with‬
‭Example‬ ‭works is to experiment with it.‬
‭different parameters:‬
‭int plusFunc(int x, int y) {‬ ‭Recursion Example‬
‭Example‬
‭return x + y;‬ ‭Adding two numbers together is easy to do, but adding a range of numbers is‬
‭int myFunction(int x)‬
‭}‬ ‭more complicated. In the following example, recursion is used to add a range of‬
‭float myFunction(float x)‬
‭double plusFunc(double x, double y) {‬ ‭numbers together by breaking it down into the simple task of adding two‬
‭double myFunction(double x, double y)‬
‭return x + y;‬ ‭numbers:‬
‭Consider the following example, which have two functions that add‬
‭}‬ ‭Example‬
‭numbers of different type:‬
‭int main() {‬ ‭int sum(int k) {‬
‭Example‬
‭int myNum1 = plusFunc(8, 5);‬ ‭if (k > 0) {‬
‭int plusFuncInt(int x, int y) {‬
‭double myNum2 = plusFunc(4.3, 6.26);‬ ‭return k + sum(k - 1);‬
‭return x + y;‬
‭cout << "Int: " << myNum1 << "\n";‬ ‭} else {‬
‭}‬
‭cout << "Double: " << myNum2;‬ ‭return 0;‬
‭double plusFuncDouble(double x, double y) {‬
‭return 0;‬ ‭}‬
‭return x + y;‬
‭}‬ ‭}‬
‭}‬
‭Note: Multiple functions can have the same name as long as the number and/or‬ ‭int main() {‬
‭int main() {‬
‭type of parameters are different.‬ ‭int result = sum(10);‬
‭int myNum1 = plusFuncInt(8, 5);‬
‭cout << result;‬
‭double myNum2 = plusFuncDouble(4.3, 6.26);‬

‭C++ Recursion‬
‭return 0;‬
‭cout << "Int: " << myNum1 << "\n";‬
‭}‬
‭cout << "Double: " << myNum2;‬
‭Example Explained‬
‭return 0;‬ ‭Recursion‬
‭}‬

‭78‬ ‭79‬ ‭80‬


‭When the sum() function is called, it adds parameter k to the sum of all numbers‬ ‭Procedural programming is about writing procedures or functions that perform‬ ‭Objects‬
‭smaller than k and returns the result. When k becomes 0, the function just‬ ‭operations on the data, while object-oriented programming is about creating‬ ‭Apple‬
‭returns 0. When running, the program follows these steps:‬ ‭objects that contain both data and functions.‬ ‭Banana‬
‭Mango‬
‭10 + sum(9)‬ ‭Object-oriented programming has several advantages over procedural‬
‭10 + ( 9 + sum(8) )‬ ‭programming:‬ ‭Another example:‬
‭10 + ( 9 + ( 8 + sum(7) ) )‬
‭...‬ ‭OOP is faster and easier to execute‬ ‭Class‬
‭10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)‬ ‭OOP provides a clear structure for the programs‬ ‭Car‬
‭10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0‬ ‭OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the‬ ‭Objects‬
‭Since the function does not call itself when k is 0, the program stops there and‬ ‭code easier to maintain, modify and debug‬ ‭Volvo‬
‭returns the result.‬ ‭OOP makes it possible to create full reusable applications with less code and‬ ‭Audi‬
‭The developer should be very careful with recursion as it can be quite easy to‬ ‭shorter development time‬ ‭Toyota‬
‭slip into writing a function which never terminates, or one that uses excess‬ ‭Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the‬
‭amounts of memory or processor power. However, when written correctly‬ ‭repetition of code. You should extract out the codes that are common for the‬ ‭So, a class is a template for objects, and an object is an instance of a class.‬
‭recursion can be a very efficient and mathematically-elegant approach to‬ ‭application, and place them at a single place and reuse them instead of‬ ‭When the individual objects are created, they inherit all the variables and‬
‭programming.‬ ‭repeating it.‬ ‭functions from the class.‬
‭You will learn much more about classes and objects in the next chapter.‬

‭C++ OOP‬
‭C++ What are Classes and Objects?‬
‭Classes and objects are the two main aspects of object-oriented programming.‬

‭C++ What is OOP?‬


‭Look at the following illustration to see the difference between class and‬ ‭C++ Classes and Objects‬
‭objects:‬
‭OOP stands for Object-Oriented Programming.‬ ‭C++ Classes/Objects‬
‭class‬
‭C++ is an object-oriented programming language.‬
‭Fruit‬

‭81‬ ‭82‬ ‭83‬

‭Everything in C++ is associated with classes and objects, along with its‬ ‭Inside the class, there is an integer variable myNum and a string variable‬ ‭myObj.myString = "Some text";‬
‭attributes and methods. For example: in real life, a car is an object. The car has‬ ‭myString. When variables are declared within a class, they are called attributes.‬ ‭// Print attribute values‬
‭attributes, such as weight and color, and methods, such as drive and brake.‬ ‭At last, end the class definition with a semicolon ;.‬ ‭cout << myObj.myNum << "\n";‬
‭Create an Object‬ ‭cout << myObj.myString;‬
‭Attributes and methods are basically variables and functions that belongs to the‬ ‭In C++, an object is created from a class. We have already created the class‬ ‭return 0;‬
‭class. These are often referred to as "class members".‬ ‭named MyClass, so now we can use this to create objects.‬ ‭}‬
‭Multiple Objects‬
‭A class is a user-defined data type that we can use in our program, and it works‬ ‭To create an object of MyClass, specify the class name, followed by the object‬ ‭You can create multiple objects of one class:‬
‭as an object constructor, or a "blueprint" for creating objects.‬ ‭name.‬
‭Example‬
‭Create a Class‬ ‭To access the class attributes (myNum and myString), use the dot syntax (.) on‬ ‭// Create a Car class with some attributes‬
‭To create a class, use the class keyword:‬ ‭the object:‬ ‭class Car {‬
‭Example‬ ‭public:‬
‭Create a class called "MyClass":‬ ‭Example‬ ‭string brand;‬
‭Create an object called "myObj" and access the attributes:‬ ‭string model;‬
‭class MyClass { // The class‬ ‭int year;‬
‭public: // Access specifier‬ ‭class MyClass { // The class‬ ‭};‬
‭int myNum; // Attribute (int variable)‬ ‭public: // Access specifier‬ ‭int main() {‬
‭string myString; // Attribute (string variable)‬ ‭int myNum; // Attribute (int variable)‬ ‭// Create an object of Car‬
‭};‬ ‭string myString; // Attribute (string variable)‬ ‭Car carObj1;‬
‭Example explained‬ ‭};‬ ‭carObj1.brand = "BMW";‬
‭The class keyword is used to create a class called MyClass.‬ ‭int main() {‬ ‭carObj1.model = "X5";‬
‭The public keyword is an access specifier, which specifies that members‬ ‭MyClass myObj; // Create an object of MyClass‬ ‭carObj1.year = 1999;‬
‭(attributes and methods) of the class are accessible from outside the class. You‬ ‭// Access attributes and set values‬ ‭// Create another object of Car‬
‭will learn more about access specifiers later.‬ ‭myObj.myNum = 15;‬ ‭Car carObj2;‬

‭84‬ ‭85‬ ‭86‬

‭carObj2.brand = "Ford";‬ ‭void myMethod() { // Method/function defined inside the class‬ ‭myObj.myMethod(); // Call the method‬
‭carObj2.model = "Mustang";‬ ‭cout << "Hello World!";‬ ‭return 0;‬
‭carObj2.year = 1969;‬ ‭}‬ ‭}‬
‭// Print attribute values‬ ‭};‬ ‭Parameters‬
‭cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<‬ ‭int main() {‬ ‭You can also add parameters:‬
‭"\n";‬ ‭MyClass myObj; // Create an object of MyClass‬ ‭Example‬
‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬ ‭myObj.myMethod(); // Call the method‬ ‭#include <iostream>‬
‭"\n";‬ ‭return 0;‬ ‭using namespace std;‬
‭return 0;‬ ‭}‬ ‭class Car {‬
‭}‬ ‭To define a function outside the class definition, you have to declare it inside‬ ‭public:‬
‭the class and then define it outside of the class. This is done by specifiying the‬ ‭int speed(int maxSpeed);‬

‭C++ Class Methods‬


‭name of the class, followed the scope resolution :: operator, followed by the‬ ‭};‬
‭name of the function:‬ ‭int Car::speed(int maxSpeed) {‬
‭return maxSpeed;‬
‭Class Methods‬
‭Outside Example‬ ‭}‬
‭Methods are functions that belongs to the class.‬
‭class MyClass { // The class‬ ‭int main() {‬
‭There are two ways to define functions that belongs to a class:‬
‭public: // Access specifier‬ ‭Car myObj; // Create an object of Car‬
‭Inside class definition‬
‭void myMethod(); // Method/function declaration‬ ‭cout << myObj.speed(200); // Call the method with an argument‬
‭Outside class definition‬
‭};‬ ‭return 0;‬
‭In the following example, we define a function inside the class, and we name it‬
‭// Method/function definition outside the class‬ ‭}‬
‭"myMethod".‬
‭void MyClass::myMethod() {‬
‭Note: You access methods just like you access attributes; by creating an object‬
‭cout << "Hello World!";‬
‭of the class and using the dot syntax (.):‬
‭Inside Example‬
‭}‬ ‭C++ Constructors‬
‭int main() {‬
‭class MyClass { // The class‬ ‭Constructors‬
‭MyClass myObj; // Create an object of MyClass‬
‭public: // Access specifier‬

‭87‬ ‭88‬ ‭89‬


‭A constructor in C++ is a special method that is automatically called when an‬ ‭The following class have brand, model and year attributes, and a constructor‬ ‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬
‭object of a class is created.‬ ‭with different parameters. Inside the constructor we set the attributes equal to‬ ‭"\n";‬
‭To create a constructor, use the same name as the class, followed by parentheses‬ ‭the constructor parameters (brand=x, etc). When we call the constructor (by‬ ‭return 0;‬
‭():‬ ‭creating an object of the class), we pass parameters to the constructor, which‬ ‭}‬
‭Example‬ ‭will set the value of the corresponding attributes to the same:‬ ‭Just like functions, constructors can also be defined outside the class. First,‬
‭class MyClass { // The class‬ ‭declare the constructor inside the class, and then define it outside of the class by‬
‭public: // Access specifier‬ ‭Example‬ ‭specifying the name of the class, followed by the scope resolution :: operator,‬
‭MyClass() { // Constructor‬ ‭class Car { // The class‬ ‭followed by the name of the constructor (which is the same as the class):‬
‭cout << "Hello World!";‬ ‭public: // Access specifier‬
‭}‬ ‭string brand; // Attribute‬ ‭Example‬
‭};‬ ‭string model; // Attribute‬ ‭class Car { // The class‬
‭int main() {‬ ‭int year; // Attribute‬ ‭public: // Access specifier‬
‭MyClass myObj; // Create an object of MyClass (this will call the‬ ‭Car(string x, string y, int z) { // Constructor with parameters‬ ‭string brand; // Attribute‬
‭constructor)‬ ‭brand = x;‬ ‭string model; // Attribute‬
‭return 0;‬ ‭model = y;‬ ‭int year; // Attribute‬
‭}‬ ‭year = z;‬ ‭Car(string x, string y, int z); // Constructor declaration‬
‭Note: The constructor has the same name as the class, it is always public, and it‬ ‭}‬ ‭};‬
‭does not have any return value.‬ ‭};‬ ‭// Constructor definition outside the class‬
‭int main() {‬ ‭Car::Car(string x, string y, int z) {‬

‭Constructor Parameters‬
‭// Create Car objects and call the constructor with different values‬ ‭brand = x;‬
‭Car carObj1("BMW", "X5", 1999);‬ ‭model = y;‬
‭Car carObj2("Ford", "Mustang", 1969);‬ ‭year = z;‬
‭Constructors can also take parameters (just like regular functions), which can be‬
‭// Print values‬ ‭}‬
‭useful for setting initial values for attributes.‬
‭cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<‬ ‭int main() {‬
‭"\n";‬ ‭// Create Car objects and call the constructor with different values‬

‭90‬ ‭91‬ ‭92‬

‭Car carObj1("BMW", "X5", 1999);‬ ‭However, what if we want members to be private and hidden from the outside‬
‭Car carObj2("Ford", "Mustang", 1969);‬ ‭world?‬ ‭error: y is private‬
‭// Print values‬ ‭Note: It is possible to access private members of a class using a public method‬
‭cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<‬ ‭In C++, there are three access specifiers:‬ ‭inside the same class. See the next chapter (Encapsulation) on how to do this.‬
‭"\n";‬ ‭public - members are accessible from outside the class‬
‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬ ‭private - members cannot be accessed (or viewed) from outside the class‬ ‭Tip: It is considered good practice to declare your class attributes as private (as‬
‭"\n";‬ ‭protected - members cannot be accessed from outside the class, however, they‬ ‭often as you can). This will reduce the possibility of yourself (or others) to mess‬
‭return 0;‬ ‭can be accessed in inherited classes. You will learn more about Inheritance later.‬ ‭up the code. This is also the main ingredient of the Encapsulation concept,‬
‭}‬ ‭In the following example, we demonstrate the differences between public and‬ ‭which you will learn more about in the next chapter.‬
‭private members:‬ ‭Note: By default, all members of a class are private if you don't specify an access‬

‭C++ Access Specifiers‬


‭specifier:‬
‭Example‬
‭class MyClass {‬ ‭Example‬
‭Access Specifiers‬
‭public: // Public access specifier‬ ‭class MyClass {‬
‭By now, you are quite familiar with the public keyword that appears in all of our‬
‭int x; // Public attribute‬ ‭int x; // Private attribute‬
‭class examples:‬
‭private: // Private access specifier‬ ‭int y; // Private attribute‬
‭Example‬
‭int y; // Private attribute‬ ‭};‬
‭class MyClass { // The class‬
‭};‬
‭public: // Access specifier‬
‭int main() {‬

‭};‬
‭// class members goes here‬
‭MyClass myObj;‬ ‭C++ Encapsulation‬
‭myObj.x = 25; // Allowed (public)‬
‭The public keyword is an access specifier. Access specifiers define how the‬ ‭Encapsulation‬
‭myObj.y = 50; // Not allowed (private)‬
‭members (attributes and methods) of a class can be accessed. In the example‬ ‭The meaning of Encapsulation, is to make sure that "sensitive" data is hidden‬
‭return 0;‬
‭above, the members are public - which means that they can be accessed and‬ ‭from users. To achieve this, you must declare class variables/attributes as private‬
‭}‬
‭modified from outside the code.‬ ‭(cannot be accessed from outside the class). If you want others to read or modify‬
‭If you try to access a private member, an error occurs:‬
‭the value of a private member, you can provide public get and set methods.‬

‭93‬ ‭94‬ ‭95‬

‭}‬
‭Access Private Members‬ ‭Example explained‬ ‭In the example below, the Car class (child) inherits the attributes and methods‬
‭To access a private attribute, use public "get" and "set" methods:‬ ‭The salary attribute is private, which have restricted access.‬ ‭from the Vehicle class (parent):‬
‭Example‬ ‭The public setSalary() method takes a parameter (s) and assigns it to the salary‬ ‭Example‬
‭#include <iostream>‬ ‭attribute (salary = s).‬ ‭// Base class‬
‭using namespace std;‬ ‭The public getSalary() method returns the value of the private salary attribute.‬ ‭class Vehicle {‬
‭class Employee {‬ ‭Inside main(), we create an object of the Employee class. Now we can use the‬ ‭public:‬
‭private:‬ ‭setSalary() method to set the value of the private attribute to 50000. Then we call‬ ‭string brand = "Ford";‬
‭// Private attribute‬ ‭the getSalary() method on the object to return the value.‬ ‭void honk() {‬
‭int salary;‬ ‭cout << "Tuut, tuut! \n" ;‬
‭public:‬ ‭Why Encapsulation?‬ ‭}‬
‭// Setter‬ ‭It is considered good practice to declare your class attributes as private (as often‬ ‭};‬
‭void setSalary(int s) {‬ ‭as you can). Encapsulation ensures better control of your data, because you (or‬ ‭// Derived class‬
‭salary = s;‬ ‭others) can change one part of the code without affecting other parts‬ ‭class Car: public Vehicle {‬
‭}‬ ‭Increased security of data‬ ‭public:‬
‭// Getter‬ ‭string model = "Mustang";‬
‭int getSalary() {‬
‭C++ Inheritance‬
‭};‬
‭return salary;‬ ‭int main() {‬
‭}‬ ‭Car myCar;‬
‭Inheritance‬
‭};‬ ‭myCar.honk();‬
‭In C++, it is possible to inherit attributes and methods from one class to‬
‭int main() {‬ ‭cout << myCar.brand + " " + myCar.model;‬
‭another. We group the "inheritance concept" into two categories:‬
‭Employee myObj;‬ ‭return 0;‬
‭myObj.setSalary(50000);‬ ‭}‬
‭derived class (child) - the class that inherits from another class‬
‭cout << myObj.getSalary();‬ ‭Why And When To Use "Inheritance"?‬
‭base class (parent) - the class being inherited from‬
‭return 0;‬
‭To inherit from a class, use the : symbol.‬

‭96‬ ‭97‬ ‭98‬


‭- It is useful for code reusability: reuse attributes and methods of an existing‬ ‭int main() {‬ ‭};‬
‭class when you create a new class.‬ ‭MyGrandChild myObj;‬ ‭// Derived class‬
‭myObj.myFunction();‬ ‭class MyChildClass: public MyClass, public MyOtherClass {‬

‭C++ Multilevel Inheritance‬


‭return 0;‬ ‭};‬
‭}‬ ‭int main() {‬
‭MyChildClass myObj;‬
‭Multilevel Inheritance‬

‭C++ Multiple Inheritance‬


‭myObj.myFunction();‬
‭A class can also be derived from one class, which is already derived from‬
‭myObj.myOtherFunction();‬
‭another class.‬
‭return 0;‬
‭Multiple Inheritance‬
‭}‬
‭In the following example, MyGrandChild is derived from class MyChild (which‬ ‭A class can also be derived from more than one base class, using a‬
‭is derived from MyClass).‬ ‭comma-separated list:‬
‭Example‬
‭// Base class (parent)‬
‭Example‬
‭// Base class‬
‭C++ Inheritance Access‬
‭class MyClass {‬ ‭class MyClass {‬ ‭Access Specifiers‬
‭public:‬ ‭public:‬ ‭You learned from the Access Specifiers chapter that there are three specifiers‬
‭void myFunction() {‬ ‭void myFunction() {‬ ‭available in C++. Until now, we have only used public (members of a class are‬
‭cout << "Some content in parent class." ;‬ ‭cout << "Some content in parent class." ;‬ ‭accessible from outside the class) and private (members can only be accessed‬
‭}‬ ‭}‬ ‭within the class). The third specifier, protected, is similar to private, but it can‬
‭};‬ ‭};‬ ‭also be accessed in the inherited class:‬
‭// Derived class (child)‬ ‭// Another base class‬ ‭Example‬
‭class MyChild: public MyClass {‬ ‭class MyOtherClass {‬ ‭// Base class‬
‭};‬ ‭public:‬ ‭class Employee {‬
‭// Derived class (grandchild)‬ ‭void myOtherFunction() {‬ ‭protected: // Protected access specifier‬
‭class MyGrandChild: public MyChild {‬ ‭cout << "Some content in another class." ;‬ ‭int salary;‬
‭};‬ ‭}‬ ‭};‬

‭99‬ ‭100‬ ‭101‬

‭// Derived class‬ ‭class Dog : public Animal {‬


‭class Programmer: public Employee {‬ ‭Like we specified in the previous chapter; Inheritance lets us inherit attributes‬ ‭public:‬
‭public:‬ ‭and methods from another class. Polymorphism uses those methods to perform‬ ‭void animalSound() {‬
‭int bonus;‬ ‭different tasks. This allows us to perform a single action in different ways.‬ ‭cout << "The dog says: bow wow \n";‬
‭void setSalary(int s) {‬ ‭}‬
‭salary = s;‬ ‭For example, think of a base class called Animal that has a method called‬ ‭};‬
‭}‬ ‭animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds -‬ ‭Remember from the Inheritance chapter that we use the : symbol to inherit from‬
‭int getSalary() {‬ ‭And they also have their own implementation of an animal sound (the pig oinks,‬ ‭a class.‬
‭return salary;‬ ‭and the cat meows, etc.):‬ ‭Now we can create Pig and Dog objects and override the animalSound() method:‬
‭}‬ ‭Example‬ ‭Example‬
‭};‬ ‭// Base class‬ ‭// Base class‬
‭int main() {‬ ‭class Animal {‬ ‭class Animal {‬
‭Programmer myObj;‬ ‭public:‬ ‭public:‬
‭myObj.setSalary(50000);‬ ‭void animalSound() {‬ ‭void animalSound() {‬
‭myObj.bonus = 15000;‬ ‭cout << "The animal makes a sound \n";‬ ‭cout << "The animal makes a sound \n";‬
‭cout << "Salary: " << myObj.getSalary() << "\n";‬ ‭}‬ ‭}‬
‭cout << "Bonus: " << myObj.bonus << "\n";‬ ‭};‬ ‭};‬
‭return 0;‬ ‭// Derived class‬ ‭// Derived class‬
‭}‬ ‭class Pig : public Animal {‬ ‭class Pig : public Animal {‬
‭public:‬ ‭public:‬

‭C++ Polymorphism‬
‭void animalSound() {‬ ‭void animalSound() {‬
‭cout << "The pig says: wee wee \n";‬ ‭cout << "The pig says: wee wee \n";‬
‭}‬ ‭}‬
‭Polymorphism‬
‭};‬ ‭};‬
‭Polymorphism means "many forms", and it occurs when we have many classes‬
‭// Derived class‬ ‭// Derived class‬
‭that are related to each other by inheritance.‬

‭102‬ ‭103‬ ‭104‬

‭class Dog : public Animal {‬ ‭Example‬ ‭MyFile.close();‬


‭public:‬ ‭#include <iostream>‬ ‭}‬
‭void animalSound() {‬ ‭#include <fstream>‬ ‭Why do we close the file?‬
‭cout << "The dog says: bow wow \n";‬ ‭There are three classes included in the fstream library, which are used to create,‬ ‭It is considered good practice, and it can clean up unnecessary memory space.‬
‭}‬ ‭write or read files:‬
‭};‬ ‭Class‬ ‭Description‬ ‭Read a File‬
‭int main() {‬ ‭ofstream‬ ‭Creates and writes to files‬ ‭To read from a file, use either the ifstream or fstream class, and the name of the‬
‭Animal myAnimal;‬ ‭ifstream‬ ‭Reads from files‬ ‭file.‬
‭Pig myPig;‬ ‭fstream‬ ‭A combination of ofstream and ifstream: creates, reads, and‬
‭Dog myDog;‬ ‭writes to files‬ ‭Note that we also use a while loop together with the getline() function (which‬
‭myAnimal.animalSound();‬ ‭Create and Write To a File‬ ‭belongs to the ifstream class) to read the file line by line, and to print the‬
‭myPig.animalSound();‬ ‭To create a file, use either the ofstream or fstream class, and specify the name of‬ ‭content of the file:‬
‭myDog.animalSound();‬ ‭the file.‬ ‭Example‬
‭return 0;‬ ‭// Create a text string, which is used to output the text file‬
‭}‬ ‭To write to the file, use the insertion operator (<<).‬ ‭string myText;‬
‭Why And When To Use "Inheritance" and "Polymorphism"?‬ ‭Example‬ ‭// Read from the text file‬
‭- It is useful for code reusability: reuse attributes and methods of an existing‬ ‭#include <iostream>‬ ‭ifstream MyReadFile("filename.txt");‬
‭class when you create a new class.‬ ‭#include <fstream>‬ ‭// Use a while loop together with the getline() function to read the file‬
‭using namespace std;‬ ‭line by line‬

‭C++ Files‬
‭int main() {‬ ‭while (getline (MyReadFile, myText)) {‬
‭// Create and open a text file‬ ‭// Output the text from the file‬
‭ofstream MyFile("filename.txt");‬ ‭cout << myText;‬
‭C++ Files‬
‭// Write to the file‬ ‭}‬
‭The fstream library allows us to work with files.‬
‭MyFile << "Files can be tricky, but it is fun enough!";‬ ‭// Close the file‬
‭To use the fstream library, include both the standard <iostream> AND the‬
‭// Close the file‬ ‭MyReadFile.close();‬
‭<fstream> header file:‬

‭105‬ ‭106‬ ‭107‬


‭// Block of code to handle errors‬

‭C++ Exceptions‬
‭}‬ ‭If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater‬
‭Consider the following example:‬ ‭than 18), the catch block is skipped:‬

‭C++ Exceptions‬
‭Example‬ ‭Example‬
‭When executing C++ code, different errors can occur: coding errors made by the‬
‭try {‬ ‭int age = 20;‬
‭programmer, errors due to wrong input, or other unforeseeable things.‬
‭int age = 15;‬ ‭You can also use the throw keyword to output a reference number, like a custom‬
‭When an error occurs, C++ will normally stop and generate an error message.‬
‭if (age >= 18) {‬ ‭error number/code for organizing purposes:‬
‭The technical term for this is: C++ will throw an exception (throw an error).‬
‭cout << "Access granted - you are old enough.";‬
‭} else {‬ ‭Example‬
‭C++ try and catch‬
‭throw (age);‬ ‭try {‬
‭Exception handling in C++ consist of three keywords: try, throw and catch:‬
‭}‬ ‭int age = 15;‬
‭The try statement allows you to define a block of code to be tested for errors‬
‭}‬ ‭if (age >= 18) {‬
‭while it is being executed.‬
‭catch (int myNum) {‬ ‭cout << "Access granted - you are old enough.";‬
‭The throw keyword throws an exception when a problem is detected, which lets‬
‭cout << "Access denied - You must be at least 18 years old.\n";‬ ‭} else {‬
‭us create a custom error.‬
‭cout << "Age is: " << myNum;‬ ‭throw 505;‬
‭The catch statement allows you to define a block of code to be executed, if an‬
‭}‬ ‭}‬
‭error occurs in the try block.‬
‭Example explained‬ ‭}‬
‭The try and catch keywords come in pairs:‬
‭We use the try block to test some code: If the age variable is less than 18, we will‬ ‭catch (int myNum) {‬
‭throw an exception, and handle it in our catch block.‬ ‭cout << "Access denied - You must be at least 18 years old.\n";‬
‭Example‬
‭cout << "Error number: " << myNum;‬
‭try {‬
‭In the catch block, we catch the error and do something about it. The catch‬ ‭}‬
‭// Block of code to try‬
‭statement takes a parameter: in our example we use an int variable (myNum)‬ ‭Handle Any Type of Exceptions (...)‬
‭throw exception; // Throw an exception when a problem arise‬
‭(because we are throwing an exception of int type in the try block (age)), to‬ ‭If you do not know the throw type used in the try block, you can use the "three‬
‭}‬
‭output the value of age.‬ ‭dots" syntax (...) inside the catch block, which will handle any type of exception:‬
‭catch () {‬

‭108‬ ‭109‬ ‭110‬

‭Example‬ ‭Const‬ ‭Defines a variable or parameter as a constant (unchangeable) or‬


‭Example‬ ‭int x, y;‬ ‭specifies that a class method does not modify attributes of the class‬
‭try {‬ ‭int sum;‬ ‭continue‬ ‭Continues to the next iteration of a loop‬
‭int age = 15;‬ ‭cout << "Type a number: ";‬ ‭default‬ ‭Specifies the default block of code in a switch statement‬
‭if (age >= 18) {‬ ‭cin >> x;‬ ‭delete‬ ‭Frees dynamic memory‬
‭cout << "Access granted - you are old enough.";‬ ‭cout << "Type another number: ";‬ ‭do‬ ‭Used together with while to create a do/while loop‬
‭} else {‬ ‭cin >> y;‬ ‭double‬ ‭A data type that is usually 64 bits long which can store fractional‬
‭throw 505;‬ ‭sum = x + y;‬ ‭numbers‬
‭}‬ ‭cout << "Sum is: " << sum;‬ ‭else‬ ‭Used in conditional statements‬
‭}‬
‭C++ Keywords‬
‭enum‬ ‭Declares an enumerated type‬
‭catch (...) {‬ ‭false‬ ‭A boolean value equivalent to 0‬
‭cout << "Access denied - You must be at least 18 years old.\n";‬ ‭float‬ ‭A data type that is usually 32 bits long which can store fractional‬
‭C++ Keywords‬
‭}‬ ‭numbers‬
‭A list of useful keywords in C++ can be found in the table below.‬

‭C++ How To Add Two Numbers‬


‭for‬ ‭Creates a for loop‬
‭Keyword‬ ‭Description‬
‭friend‬ ‭Specifies classes and functions which have‬‭access to private and‬
‭and‬ ‭An alternative way to write the logical && operator‬
‭protected members‬
‭Add Two Numbers‬ ‭and_eq‬ ‭An alternative way to write the &= assignment operator‬
‭goto‬ ‭Jumps to a line of code specified by a label‬
‭Learn how to add two numbers in C++:‬ ‭bitand‬ ‭An alternative way to write the & bitwise operator‬
‭if‬ ‭Makes a conditional statement‬
‭Example‬ ‭bitor‬ ‭An alternative way to write the | bitwise operator‬
‭int‬ ‭A data type that is usually 32 bits long which can store whole‬
‭int x = 5;‬ ‭bool‬ ‭A data type that can only store true or false values‬
‭numbers‬
‭int y = 6;‬ ‭break‬ ‭Breaks out of a loop or a switch block‬
‭long‬ ‭Ensures that an integer is at least 32 bits long (use long long to‬
‭int sum = x + y;‬ ‭case‬ ‭Marks a block of code in switch statements‬
‭ensure 64 bits)‬
‭cout << sum;‬ ‭catch‬ ‭Catches exceptions generated by try statements‬
‭namespace‬ ‭Declares a namespace‬
‭Add Two Numbers with User Input‬ ‭char‬ ‭A data type that can store a single character‬
‭new‬ ‭Reserves dynamic memory‬
‭In this example, the user must input two numbers. Then we print the sum by‬ ‭class‬ ‭Defines a class‬
‭not‬ ‭An alternative way to write the logical ! operator‬
‭calculating (adding) the two numbers:‬ ‭compl‬ ‭An alternative way to write the ~ bitwise operator‬

‭111‬ ‭112‬ ‭113‬

‭not_eq‬ ‭An alternative way to write the != comparison operator‬ ‭true‬ ‭A boolean value equivalent to 1‬ ‭acosh(x)‬ ‭Returns the hyperbolic arccosine of x‬
‭or‬ ‭An alternative way to write the logical || operator‬ ‭try‬ ‭Creates a try...catch statement‬ ‭asin(x)‬ ‭Returns the arcsine of x, in radians‬
‭or_eq‬ ‭An alternative way to write the |= assignment operator‬ ‭typedef‬ ‭Defines a custom data type‬ ‭asinh(x)‬ ‭Returns the hyperbolic arcsine of x‬
‭private‬ ‭An access modifier which makes a member only‬‭accessible‬ ‭unsigned‬ ‭Specifies that an int or char should only‬‭represent positive values‬ ‭atan(x)‬ ‭Returns the arctangent of x as a numeric‬‭value between‬
‭within the declared class‬ ‭which allows for storing numbers up to twice as large‬ ‭-PI/2 and PI/2 radians‬
‭protected‬ ‭An access modifier which makes a member‬‭only accessible‬ ‭using‬ ‭Allows variables and functions from a namespace‬‭to be used‬ ‭atan2(y, x)‬ ‭Returns the angle theta from the conversion‬‭of‬
‭within the declared class and its children‬ ‭without the namespace's prefix‬ ‭rectangular coordinates (x, y) to polar coordinates (r, theta)‬
‭public‬ ‭An access modifier which makes a member accessible from‬ ‭virtual‬ ‭Specifies that a class method is virtual‬ ‭atanh(x)‬ ‭Returns the hyperbolic arctangent of x‬
‭anywhere‬ ‭void‬ ‭Indicates a function that does not return a‬‭value or specifies a‬ ‭cbrt(x)‬ ‭Returns the cube root of x‬
‭return‬ ‭Used to return a value from a function‬ ‭pointer to a data with an unspecified type‬ ‭ceil(x)‬ ‭Returns the value of x rounded up to its nearest integer‬
‭short‬ ‭Reduces the size of an integer to 16 bits‬ ‭while‬ ‭Creates a while loop‬ ‭copysign(x, y)‬ ‭Returns the first floating point x‬‭with the sign of the‬
‭signed‬ ‭Specifies that an int or char can represent‬‭positive and negative‬ ‭xor‬ ‭An alternative way to write the ^ bitwise operator‬ ‭second floating point y‬
‭values (this is the default so the keyword is not usually necessary)‬ ‭xor_eq‬ ‭An alternative way to write the ^= assignment operator‬ ‭cos(x)‬ ‭Returns the cosine of x (x is in radians)‬
‭sizeof‬ ‭An operator that returns the amount of memory occupied by a‬ ‭cosh(x)‬ ‭Returns the hyperbolic cosine of x‬
‭variable or data type‬
‭C++ Math Functions‬
‭exp(x)‬ ‭Returns the value of Ex‬
‭static‬ ‭Specifies that an attribute or method belongs‬‭to the class itself‬ ‭exp2(x)‬ ‭Returns the value of 2x‬
‭instead of instances of the classSpecifies that a variable in a function keeps its‬ ‭expm1(x)‬ ‭Returns ex-1‬
‭C++ Math Functions‬
‭value after the function ends‬ ‭erf(x)‬ ‭Returns the value of the error function at x‬
‭The <cmath> library has many functions that allow you to perform mathematical‬
‭struct‬ ‭Defines a structure‬ ‭erfc(x)‬ ‭Returns the value of the complementary error function at‬
‭tasks on numbers.‬
‭switch‬ ‭Selects one of many code blocks to be executed‬ ‭x‬
‭template‬ ‭Declares a template class or template function‬ ‭fabs(x)‬ ‭Returns the absolute value of a floating x‬
‭A list of all math functions can be found in the table below:‬
‭this‬ ‭A variable that is available inside class methods‬‭and constructors‬ ‭fdim(x)‬ ‭Returns the positive difference between x and y‬
‭which contians a pointer to a class instance‬ ‭floor(x)‬ ‭Returns the value of x rounded down to its nearest integer‬
‭Function‬ ‭Description‬
‭throw‬ ‭Creates a custom error which can be caught‬‭by a try...catch‬ ‭fma(x, y, z)‬ ‭Returns x*y+z without losing precision‬
‭abs(x)‬ ‭Returns the absolute value of x‬
‭statement‬ ‭fmax(x, y)‬ ‭Returns the highest value of a floating x and y‬
‭acos(x)‬ ‭Returns the arccosine of x, in radians‬

‭114‬ ‭115‬ ‭116‬


‭fmin(x, y)‬ ‭Returns the lowest value of a floating x and y‬ ‭modf(x, y)‬ ‭Returns the decimal part of x and writes the integer part‬
‭fmod(x, y)‬ ‭Returns the floating point remainder of x/y‬ ‭to the memory at the pointer y‬
‭frexp(x, y)‬ ‭With x expressed as m*2n, returns the‬‭value of m (a value between‬ ‭nan(s)‬ ‭Returns a NaN (Not a Number) value‬
‭0.5 and 1.0) and writes the value of n to the memory at the pointer y‬ ‭nearbyint(x)‬ ‭Returns x rounded to a nearby integer‬
‭hypot(x, y)‬ ‭Returns sqrt(x2 +y2) without intermediate overflow or‬ ‭nextafter(x, y)‬ ‭Returns the closest floating point‬‭number to x in the‬
‭underflow‬ ‭direction of y‬
‭ilogb(x)‬ ‭Returns the integer part of the floating-point‬‭base‬ ‭nexttoward(x, y)‬ ‭Returns the closest floating point‬‭number to x in the‬
‭logarithm of x‬ ‭direction of y‬
‭ldexp(x, y)‬ ‭Returns x*2y‬ ‭pow(x, y)‬ ‭Returns the value of x to the power of y‬
‭lgamma(x)‬ ‭Returns the logarithm of the absolute value‬‭of the gamma‬ ‭remainder(x, y)‬ ‭Return the remainder of x/y rounded to the nearest‬
‭function at x‬ ‭integer‬
‭llrint(x)‬ ‭Rounds x to a nearby integer and returns‬‭the result as a‬ ‭remquo(x, y, z)‬ ‭Calculates x/y rounded to the nearest‬‭integer, writes the‬
‭long long integer‬ ‭result to the memory at the pointer z and returns the remainder.‬
‭llround(x)‬ ‭Rounds x to the nearest integer and returns the result as a‬ ‭rint(x)‬ ‭Returns x rounded to a nearby integer‬
‭long long integer‬ ‭round(x)‬ ‭Returns x rounded to the nearest integer‬
‭log(x)‬ ‭Returns the natural logarithm of x‬ ‭scalbln(x, y)‬ ‭Returns x*Ry (R is usually 2)‬
‭log10(x)‬ ‭Returns the base 10 logarithm of x‬ ‭scalbn(x, y)‬ ‭Returns x*Ry (R is usually 2)‬
‭log1p(x)‬ ‭Returns the natural logarithm of x+1‬ ‭sin(x)‬ ‭Returns the sine of x (x is in radians)‬
‭log2(x)‬ ‭Returns the base 2 logarithm of the absolute value of x‬ ‭sinh(x)‬ ‭Returns the hyperbolic sine of x‬
‭logb(x)‬ ‭Returns the floating-point base logarithm‬‭of the absolute‬ ‭sqrt(x)‬ ‭Returns the square root of x‬
‭value of x‬ ‭tan(x)‬ ‭Returns the tangent of x (x is in radians)‬
‭lrint(x)‬ ‭Rounds x to a nearby integer and returns‬‭the result as a‬ ‭tanh(x)‬ ‭Returns the hyperbolic tangent of x‬
‭long integer‬ ‭tgamma(x)‬ ‭Returns the value of the gamma function at x‬
‭lround(x)‬ ‭Rounds x to the nearest integer and returns‬‭the result as a‬ ‭trunc(x)‬ ‭Returns the integer part of x‬
‭long integer‬

‭117‬ ‭118‬

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy