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

C++ Print

The document provides a detailed guide to C++ syntax and features. It covers topics like C++ output, variables, data types, operators, strings, math functions, conditions, loops, arrays, structures, functions, classes, objects, inheritance and polymorphism. Each topic spans multiple pages with code examples and explanations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C++ Print

The document provides a detailed guide to C++ syntax and features. It covers topics like C++ output, variables, data types, operators, strings, math functions, conditions, loops, arrays, structures, functions, classes, objects, inheritance and polymorphism. Each topic spans multiple pages with code examples and explanations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

‭0‬

‭C++ Menu‬
‭Title‬ ‭page‬‭number‬
‭C++ Syntax‬ ‭2-3‬
‭C++ Output‬ ‭4-7‬
‭C++ Comments‬ ‭7-8‬

‭C++‬
‭C++ Variables‬ ‭8-13‬
‭C++ User Input‬ ‭13-14‬
‭C++ Data Types‬ ‭14-18‬
‭C++ Operators‬ ‭18-22‬
‭C++ Strings‬ ‭23-30‬
‭C++ Math‬ ‭30-32‬
‭C++ Booleans‬ ‭32-34‬
‭C++ Conditions(if……else)‬ ‭35-39‬
‭C++ Switch‬ ‭39-42‬

‭A complete guide to‬ ‭C++ While Loop‬


‭C++ For Loop‬
‭42-44‬
‭44-46‬

‭c++‬
‭C++ Break/Continue‬ ‭46-48‬
‭C++ Arrays‬ ‭48-59‬
‭C++ Structures‬ ‭59-63‬
‭C++ References‬ ‭63-64‬
‭C++ Pointers‬ ‭64-67‬
‭C++ Functions‬ ‭67-71‬
‭C++ Function Parameters‬ ‭71-77‬
‭1‬

‭C++ Function Overloading 78-79‬ ‭return 0;‬


‭C++ Recursion‬ ‭79-81‬ ‭}‬
‭C++ Classes‬ ‭Example explained‬
‭C++ OOP‬ ‭81-83‬ ‭Line 1: #include <iostream> is a header file library that lets us work with input‬
‭C++ Classes/Objects‬ ‭83-87‬ ‭and output objects, such as cout (used in line 5). Header files add functionality to‬
‭C++ Class Methods‬ ‭87-89‬ ‭C++ programs.‬
‭C++ Constructors 89-93‬ ‭Line 2: using namespace std means that we can use names for objects and‬
‭C++ Access Specifiers 93-95‬ ‭variables from the standard library.‬
‭C++ Encapsulation 95-97‬
‭C++ Inheritance 97-102‬ ‭Don't worry if you don't understand how #include <iostream> and using‬
‭C++ Polymorphism 102-105‬ ‭namespace std works. Just think of it as something that (almost) always appears‬
‭C++ Files 105-107‬ ‭in your program.‬
‭C++ Exceptions 108-111‬
‭Add Two Numbers 111-112‬ ‭Line 3: A blank line. C++ ignores white space. But we use it to make the code‬
‭C++ Reference‬ ‭more readable.‬
‭C++ Keywords 112-115‬ ‭Line 4: Another thing that always appear in a C++ program is int main(). This is‬
‭C++ Math Functions 115-118‬ ‭called a function. Any code inside its curly brackets {} will be executed.‬

‭C++ Syntax‬
‭Line 5: cout (pronounced "see-out") is an object used together with the insertion‬
‭operator (<<) to output/print text. In our example, it will output "Hello World!".‬
‭Note: Every C++ statement ends with a semicolon ;.‬
‭C++ Syntax‬
‭ et's break up the following code to understand it better:‬
L ‭Note: The body of int main() could also been written as:‬
‭Example‬
‭int main () { cout << "Hello world! "; return 0; }‬
‭#include <iostream>‬
‭Remember: The compiler ignores white spaces. However, multiple lines makes‬
‭using namespace std;‬
‭the code more readable.‬
‭int main() {‬
‭Line 6: return 0 ends the main function.‬
‭cout << "Hello World!";‬
‭2‬ ‭3‬
‭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:‬
‭Omitting Namespace‬ ‭Example‬

‭You might see some C++ programs that runs without the standard namespace‬ ‭#include <iostream>‬

‭library. The using namespace std line can be omitted and replaced with the std‬ ‭using namespace std;‬

‭keyword, followed by the :: operator for some objects:‬ ‭int main() {‬

‭Example‬ ‭cout << "Hello World!";‬

‭#include <iostream>‬ ‭cout << "I am learning C++";‬

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

‭std::cout << "Hello World!";‬ ‭}‬

‭return 0;‬ ‭C++ New Lines‬

‭}‬ ‭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:‬
‭Example‬
‭C++ Output (Print Text)‬ ‭#include <iostream>‬
‭using namespace std;‬
‭C++ Output (Print Text)‬
‭int main() {‬
‭The cout object, together with the << operator, is used to output values/print‬
‭cout << "Hello World! \n";‬
‭text:‬
‭cout << "I am learning C++";‬
‭Example‬
‭return 0;‬
‭#include <iostream>‬
‭}‬
‭using namespace std;‬
‭Tip : Two \n characters after each other will create a blank line:‬
‭int main() {‬
‭cout << "Hello World!";‬
‭Example‬
‭return 0; }‬
‭#include <iostream>‬

‭4‬ ‭5‬

‭using namespace std;‬ ‭\t‬ ‭Creates a horizontal tab‬


‭int main() {‬ ‭\\‬ ‭Inserts a backslash character (\)‬
‭cout << "Hello World! \n\n";‬ ‭\"‬ ‭Inserts a double quote character‬
‭cout << "I am learning C++";‬
‭return 0;‬ ‭C++ Comments‬
‭}‬
‭C++ Comments‬
‭Another way to insert a new line, is with the endl manipulator:‬
‭Comments can be used to explain C++ code, and to make it more readable. It can‬
‭Example‬
‭also be used to prevent execution when testing alternative code. Comments can‬
‭#include <iostream>‬
‭be single-lined or multi-lined.‬
‭using namespace std;‬
‭int main() {‬
‭Single-line Comments‬
‭cout << "Hello World!" << endl;‬
‭Single-line comments start with two forward slashes (//).‬
‭cout << "I am learning C++";‬
‭Any text between // and the end of the line is ignored by the compiler (will not‬
‭return 0;‬
‭be executed).‬
‭}‬
‭This example uses a single-line comment before a line of code:‬
‭Both \n and endl are used to break lines. However, \n is most used.‬
‭Example‬
‭// This is a comment‬
‭But what is \n exactly?‬
‭cout << "Hello World!";‬
‭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:‬
‭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‬
‭C++ Multi-line Comments‬
‭Examples of other valid escape sequences are:‬
‭Multi-line comments start with /* and ends with */.‬
‭Any text between /* and */ will be ignored by the compiler:‬
‭Escape Sequence‬ ‭description‬
‭Example‬
‭6‬ ‭7‬
‭/* The code below will print the words Hello World!‬ ‭Where type is one of C++ types (such as int), and variableName is the name of‬
‭to the screen, and it is amazing */‬ ‭the variable (such as x or myName). The equal sign is used to assign values to the‬
‭cout << "Hello World!";‬ ‭variable.‬
‭Single or multi-line comments?‬ ‭To create a variable that should store a number, look at the following example:‬
‭It is up to you which you want to use. Normally, we use // for short comments,‬ ‭Example‬
‭and /* */ for longer.‬ ‭Create a variable called myNum of type int and assign it the value 15:‬

‭C++ Variables‬
‭int myNum = 15;‬
‭cout << myNum;‬
‭You can also declare a variable without assigning the value, and assign the value‬
‭C++ Variables‬
‭later:‬
‭Variables are containers for storing data values.‬
‭Example‬
‭In C++, there are different types of variables (defined with different keywords),‬
‭int myNum;‬
‭for example:‬
‭myNum = 15;‬
‭int - stores integers (whole numbers), without decimals, such as 123 or -123‬ ‭cout << myNum;‬
‭double - stores floating point numbers, with decimals, such as 19.99 or -19.99‬ ‭Note that if you assign a new value to an existing variable, it will overwrite the‬
‭char - stores single characters, such as 'a' or 'B'. Char values are surrounded by‬ ‭previous value:‬
‭single quotes‬
‭string - stores text, such as "Hello World". String values are surrounded by‬ ‭Example‬
‭double quotes‬ ‭int myNum = 15; // myNum is 15‬
‭bool - stores values with two states: true or false‬ ‭myNum = 10; // Now myNum is 10‬
‭cout << myNum; // Outputs 10‬
‭Declaring (Creating) Variables‬ ‭Other Types‬
‭To create a variable, specify the type and assign it a value:‬ ‭A demonstration of other data types:‬
‭Syntax‬
‭type variableName = value;‬ ‭Example‬

‭8‬ ‭9‬

‭int myNum = 5; // Integer (whole number without decimals)‬ ‭Example‬


‭double myFloatNum = 5.99; // Floating point number (with decimals)‬ ‭int x = 5, y = 6, z = 50;‬
‭char myLetter = 'D'; // Character‬ ‭cout << x + y + z;‬
‭string myText = "Hello"; // String (text)‬ ‭One Value to Multiple Variables‬
‭bool myBoolean = true; // Boolean (true or false)‬ ‭You can also assign the same value to multiple variables in one line:‬
‭You will learn more about the individual types in the Data Types chapter.‬ ‭Example‬
‭int x, y, z;‬
‭Display Variables‬ ‭x = y = z = 50;‬
‭The cout object is used together with the << operator to display variables.‬ ‭cout << x + y + z;‬
‭To combine both text and a variable, separate them with the << operator:‬
‭C++ Identifiers‬
‭Example‬ ‭C++ Identifiers‬
‭int myAge = 35;‬ ‭All C++ variables must be identified with unique names.‬
‭cout << "I am " << myAge << " years old.";‬ ‭These unique names are called identifiers.‬
‭Add Variables Together‬ ‭Identifiers can be short names (like x and y) or more descriptive names (age,‬
‭To add a variable to another variable, you can use the + operator:‬ ‭sum, totalVolume).‬
‭Example‬
‭int x = 5;‬ ‭Note: It is recommended to use descriptive names in order to create‬
‭int y = 6;‬ ‭understandable and maintainable code:‬
‭int sum = x + y;‬ ‭Example‬
‭cout << sum;‬ ‭// Good‬
‭int minutesPerHour = 60;‬
‭C++ Declare Multiple Variables‬ ‭// OK, but not so easy to understand what m actually is‬
‭Declare Many Variables‬ ‭int m = 60;‬
‭To declare more than one variable of the same type, use a comma-separated list:‬ ‭The general rules for naming variables are:‬

‭10‬ ‭11‬
‭This however, will not work:‬
‭Names can contain letters, digits and underscores‬ ‭const int minutesPerHour;‬
‭Names must begin with a letter or an underscore (_)‬ ‭minutesPerHour = 60; // error‬
‭Names are case-sensitive (myVar and myvar are different variables)‬
‭Names cannot contain whitespaces or special characters like !, #, %, etc.‬ ‭C++ User Input‬
‭Reserved words (like C++ keywords, such as int) cannot be used as names‬
‭C++ User Input‬

‭C++ Constants‬ ‭You have already learned that cout is used to output (print) values. Now we will‬
‭use cin to get user input.‬
‭Constants‬ ‭cin is a predefined variable that reads data from the keyboard with the‬
‭When you do not want others (or yourself) to change existing variable values, use‬ ‭extraction operator (>>).‬
‭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‬
‭unchangeable and read-only):‬ ‭variable x. Then we print the value of x:‬
‭Example‬ ‭Example‬
‭const int myNum = 15; // myNum will always be 15‬ ‭int x;‬
‭myNum = 10; // error: assignment of read-only variable 'myNum'‬ ‭cout << "Type a number: "; // Type a number and press enter‬
‭You should always declare the variable as constant when you have values that‬ ‭cin >> x; // Get user input from the keyboard‬
‭are unlikely to change:‬ ‭cout << "Your number is: " << x; // Display the input value‬
‭Example‬ ‭Good To Know‬
‭const int minutesPerHour = 60;‬
‭const float PI = 3.14;‬ ‭cout is pronounced "see-out". Used for output, and uses the insertion operator‬
‭Notes On Constants‬ ‭(<<)‬
‭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 (>>)‬
‭Example‬
‭Like this:‬ ‭Creating a Simple Calculator‬
‭const int minutesPerHour = 60;‬

‭12‬ ‭13‬

‭In this example, the user must input two numbers. Then we print the sum by‬ ‭The data type specifies the size and type of information the variable will store:‬
‭calculating (adding) the two numbers:‬

‭Data Type‬ ‭Size‬ ‭Description‬


‭Example‬
‭boolean‬ ‭1 byte‬ ‭Stores true or false values‬
‭int x, y;‬
‭char‬ ‭1 byte‬ ‭Stores a single character/letter/number, or‬
‭int sum;‬
‭ASCII values‬
‭cout << "Type a number: ";‬
‭int‬ ‭2 or 4 bytes‬ ‭Stores whole numbers, without decimals‬
‭cin >> x;‬
‭float‬ ‭4 bytes‬ ‭Stores fractional numbers, containing one or more‬
‭cout << "Type another number: ";‬
‭decimals. Sufficient for storing 6-7 decimal digits‬
‭cin >> y;‬
‭double‬ ‭8 bytes‬ ‭Stores fractional numbers, containing one or more‬
‭sum = x + y;‬
‭decimals. Sufficient for storing 15 decimal digits‬
‭cout << "Sum is: " << sum;‬
‭C++ Numeric Data Types‬
‭C++ Data Types‬
‭Numeric Types‬
‭C++ Data Types‬ ‭Use int when you need to store a whole number without decimals, like 35 or‬
‭As explained in the Variables chapter, a variable in C++ must be a specified data‬ ‭1000, and float or double when you need a floating point number (with‬
‭type:‬ ‭decimals), like 9.99 or 3.14515.‬
‭Example‬
‭int myNum = 5; // Integer (whole number)‬ ‭Int‬
‭float myFloatNum = 5.99; // Floating point number‬ ‭int myNum = 1000;‬
‭double myDoubleNum = 9.98; // Floating point number‬ ‭cout << myNum;‬
‭char myLetter = 'D'; // Character‬ ‭float‬
‭bool myBoolean = true; // Boolean‬ ‭float myNum = 5.75;‬
‭string myText = "Hello"; // String‬ ‭cout << myNum;‬
‭Basic Data Types‬ ‭Double‬
‭14‬ ‭15‬
‭double myNum = 19.99;‬ ‭Example‬
‭cout << myNum;‬ ‭bool isCodingFun = true;‬
‭float vs. double‬ ‭bool isFishTasty = false;‬
‭cout << isCodingFun; // Outputs 1 (true)‬
‭The precision of a floating point value indicates how many digits the value can‬ ‭cout << isFishTasty; // Outputs 0 (false)‬
‭have after the decimal point. The precision of float is only six or seven decimal‬ ‭Boolean values are mostly used for conditional testing‬
‭digits, while double variables have a precision of about 15 digits. Therefore it is‬
‭safer to use double for most calculations.‬ ‭C++ Character Data Types‬
‭Character Types‬
‭Scientific Numbers‬ ‭The char data type is used to store a single character. The character must be‬
‭A floating point number can also be a scientific number with an "e" to indicate‬ ‭surrounded by single quotes, like 'A' or 'c':‬
‭the power of 10:‬ ‭Example‬
‭char myGrade = 'B';‬
‭Example‬ ‭cout << myGrade;‬
‭float f1 = 35e3;‬ ‭Alternatively, if you are familiar with ASCII, you can use ASCII values to display‬
‭double d1 = 12E4;‬ ‭certain characters:‬
‭cout << f1;‬ ‭Example‬
‭cout << d1;‬ ‭char a = 65, b = 66, c = 67;‬

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


‭cout << b;‬

‭Boolean Types‬ ‭cout << c;‬

‭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.‬

‭values true or false.‬


‭When the value is returned, true = 1 and false = 0.‬
‭C++ String Data Types‬
‭String Types‬

‭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‬
‭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‬
‭be surrounded by double quotes:‬ ‭variable and another variable:‬
‭Example‬
‭Example‬ ‭int sum1 = 100 + 50; // 150 (100 + 50)‬
‭string greeting = "Hello";‬ ‭int sum2 = sum1 + 250; // 400 (150 + 250)‬
‭cout << greeting;‬ ‭int sum3 = sum2 + sum2; // 800 (400 + 400)‬
‭To use strings, you must include an additional header file in the source code, the‬ ‭C++ divides the operators into the following groups:‬
‭<string> library:‬ ‭Arithmetic operators‬
‭Assignment operators‬
‭Example‬ ‭Comparison operators‬
‭// Include the string library‬ ‭Logical operators‬
‭#include <string>‬ ‭Bitwise operators‬
‭// Create a string variable‬ ‭Arithmetic Operators‬
‭string greeting = "Hello";‬
‭// Output string value‬ ‭Arithmetic operators are used to perform common mathematical operations.‬
‭cout << greeting;‬

‭C++ Operators‬
‭Operator‬ ‭Name‬ ‭Description‬
‭Example‬

‭C++ Operators‬ ‭+‬ ‭Addition‬ ‭Adds together two values‬

‭Operators are used to perform operations on variables and values.‬ ‭x + y‬

‭In the example below, we use the + operator to add together two values:‬ ‭-‬ ‭Subtraction‬ ‭Subtracts one value from another‬

‭Example‬ ‭x - y‬

‭int x = 100 + 50;‬ ‭*‬ ‭Multiplication‬ ‭Multiplies two values‬


‭x * y‬

‭18‬ ‭19‬
‭/‬ ‭Division‬ ‭Divides one value by another‬ ‭-=‬ ‭x -= 3‬ ‭x = x - 3‬
‭x / y‬ ‭*=‬ ‭x *= 3‬ ‭x = x * 3‬
‭%‬ ‭Modulus‬ ‭Returns the division remainder‬ ‭/=‬ ‭x /= 3‬ ‭x = x / 3‬
‭x % y‬ ‭%=‬ ‭x %= 3‬ ‭x = x % 3‬
‭++‬ ‭Increment‬ ‭Increases the value of a variable by‬ ‭&=‬ ‭x &= 3‬ ‭x = x & 3‬
‭1++x‬ ‭|=‬ ‭x |= 3‬ ‭x = x | 3‬
‭--‬ ‭Decrement‬ ‭Decreases the value of a variable by‬ ‭^=‬ ‭x ^= 3‬ ‭x = x ^ 3‬
‭1--x‬ ‭>>=‬ ‭x >>= 3‬ ‭x = x >> 3‬

‭C++ Assignment Operators‬


‭<<=‬ ‭x <<= 3‬ ‭x = x << 3‬

‭Assignment Operators‬
‭C++ Comparison Operators‬
‭Assignment operators are used to assign values to variables.‬ ‭Comparison Operators‬
‭In the example below, we use the assignment operator (=) to assign the value 10‬ ‭Comparison operators are used to compare two values (or variables). This is‬
‭to a variable called x:‬ ‭important in programming, because it helps us to find answers and make‬
‭Example‬ ‭decisions.‬
‭int x = 10;‬ ‭The return value of a comparison is either 1 or 0, which means true (1) or false‬
‭The addition assignment operator (+=) adds a value to a variable:‬ ‭(0). These values are known as Boolean values, and you will learn more about‬
‭Example‬ ‭them in the Booleans and If..Else chapter.‬
‭int x = 10;‬ ‭In the following example, we use the greater than operator (>) to find out if 5 is‬
‭x += 5;‬ ‭greater than 3:‬
‭A list of all assignment operators:‬ ‭Example‬
‭int x = 5;‬
‭Operator‬ ‭Example‬ ‭Same As‬ ‭int y = 3;‬
‭=‬ ‭x = 5‬ ‭x = 5‬ ‭cout << (x > y); // returns 1 (true) because 5 is greater than 3‬
‭+=‬ ‭x += 3‬ ‭x = x + 3‬ ‭A list of all comparison operators:‬

‭20‬ ‭21‬

‭C++ Strings‬
‭Operator‬ ‭Name‬ ‭Example‬ ‭Strings are used for storing text.‬
‭==‬ ‭Equal to‬ ‭x == y‬ ‭A string variable contains a collection of characters surrounded by double‬
‭!=‬ ‭Not equal‬ ‭x != y‬ ‭quotes:‬
‭>‬ ‭Greater than‬ ‭x > y‬
‭<‬ ‭Less than‬ ‭x < y‬ ‭Example‬
‭>=‬ ‭Greater than or equal to‬ ‭x >= y‬ ‭Create a variable of type string and assign it a value:‬
‭<=‬ ‭Less than or equal to‬ ‭x <= y‬ ‭string greeting = "Hello";‬

‭C++ Logical Operators‬


‭To use strings, you must include an additional header file in the source code, the‬
‭<string> library:‬

‭Logical Operators‬
‭Example‬
‭As with comparison operators, you can also test for true (1) or false (0) values‬
‭// Include the string library‬
‭with logical operators.‬
‭#include <string>‬
‭Logical operators are used to determine the logic between variables or values:‬
‭// Create a string variable‬
‭string greeting = "Hello";‬
‭Operator‬ ‭Name‬ ‭Description‬

‭&&‬
‭Example‬
‭Logical and‬ ‭Returns true if both statements are true‬
‭C++ String Concatenation‬
‭x < 5 && x < 10‬ ‭String Concatenation‬
‭||‬ ‭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‬
‭x < 5 || x < 4‬ ‭string. This is called concatenation:‬
‭!‬ ‭Logical not‬ ‭Reverse the result, returns false if the result is true‬ ‭Example‬
‭!(x < 5‬ ‭string firstName = "John ";‬

‭C++ Strings‬
‭string lastName = "Doe";‬
‭string fullName = firstName + lastName;‬

‭22‬ ‭23‬
‭cout << fullName;‬ ‭Numbers are added. Strings are concatenated.‬
‭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:‬
‭between John and Doe on output. However, you could also add a space with‬ ‭Example‬
‭quotes (" " or ' '):‬ ‭int x = 10;‬
‭Example‬ ‭int y = 20;‬
‭string firstName = "John";‬ ‭int z = x + y; // z will be 30 (an integer)‬
‭string lastName = "Doe";‬ ‭If you add two strings, the result will be a string concatenation:‬
‭string fullName = firstName + " " + lastName;‬ ‭Example‬
‭cout << fullName;‬ ‭string x = "10";‬
‭Append‬ ‭string y = "20";‬
‭A string in C++ is actually an object, which contain functions that can perform‬ ‭string z = x + y; // z will be 1020 (a string)‬
‭certain operations on strings. For example, you can also concatenate strings‬ ‭If you try to add a number to a string, an error occurs:‬
‭with the append() function:‬ ‭Example‬
‭Example‬ ‭string x = "10";‬
‭string firstName = "John ";‬ ‭int y = 20;‬
‭string lastName = "Doe";‬ ‭string z = x + y;‬
‭string fullName = firstName.append(lastName);‬
‭cout << fullName;‬ ‭C++ String Length‬
‭C++ Numbers and Strings‬ ‭String Length‬
‭To get the length of a string, use the length() function:‬
‭Adding Numbers and Strings‬ ‭Example‬
‭WARNING!‬ ‭string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";‬
‭cout << "The length of the txt string is: " << txt.length();‬
‭C++ uses the + operator for both addition and concatenation.‬

‭24‬ ‭25‬

‭Tip: You might see some C++ programs that use the size() function to get the‬ ‭To change the value of a specific character in a string, refer to the index number,‬
‭length of a string. This is just an alias of length(). It is completely up to you if‬ ‭and use single quotes:‬
‭you want to use length() or size():‬ ‭Example‬
‭Example‬ ‭string myString = "Hello";‬
‭string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";‬ ‭myString[0] = 'J';‬
‭cout << "The length of the txt string is: " << txt.size();‬ ‭cout << myString;‬

‭C++ Access Strings‬


‭// Outputs Jello instead of Hello‬

‭Access Strings‬
‭C++ Special Characters‬
‭You can access the characters in a string by referring to its index number inside‬ ‭Strings - Special Characters‬
‭square brackets [ ].‬ ‭Because strings must be written within quotes, C++ will misunderstand this‬
‭This example prints the first character in myString:‬ ‭string, and generate an error:‬
‭Example‬ ‭string txt = "We are the so-called "Vikings" from the north.";‬
‭string myString = "Hello";‬ ‭The solution to avoid this problem, is to use the backslash escape character.‬
‭cout << myString[0];‬ ‭The backslash (\) escape character turns special characters into string‬
‭// Outputs H‬ ‭characters:‬
‭Note: String indexes start with 0: [0] is the first character. [1] is the second‬
‭character, etc.‬ ‭Escape character‬ ‭Result‬ ‭Description‬
‭\'‬ ‭'‬ ‭Single quote‬
‭This example prints the second character in myString:‬ ‭\"‬ ‭"‬ ‭Double quote‬
‭Example‬ ‭\\‬ ‭\‬ ‭Backslash‬
‭string myString = "Hello";‬ ‭The sequence \" inserts a double quote in a string:‬
‭cout << myString[1];‬ ‭Example‬
‭// Outputs e‬ ‭string txt = "We are the so-called \"Vikings\" from the north.";‬
‭Change String Characters‬ ‭The sequence \' inserts a single quote in a string:‬

‭26‬ ‭27‬
‭Example‬ ‭string fullName;‬
‭string txt = "It\'s alright.";‬ ‭cout << "Type your full name: ";‬
‭The sequence \\ inserts a single backslash in a string:‬ ‭cin >> fullName;‬
‭Example‬ ‭cout << "Your name is: " << fullName;‬
‭string txt = "The character \\ is called backslash.";‬ ‭// Type your full name: John Doe‬
‭Other popular escape characters in C++ are:‬ ‭// Your name is: John‬
‭From the example above, you would expect the program to print "John Doe", but‬
‭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‬

‭C++ User Input Strings‬


‭second:‬
‭Example‬
‭string fullName;‬
‭User Input Strings‬
‭cout << "Type your full name: ";‬
‭It is possible to use the extraction operator >> on cin to store a string entered by‬
‭getline (cin, fullName);‬
‭a user:‬
‭cout << "Your name is: " << fullName;‬
‭Example‬
‭// Type your full name: John Doe‬
‭string firstName;‬
‭// Your name is: John Doe‬
‭cout << "Type your first name: ";‬
‭cin >> firstName; // get user input from the keyboard‬
‭cout << "Your name is: " << firstName;‬
‭C++ String Namespace‬
‭// Type your first name: John‬ ‭Omitting Namespace‬
‭// Your name is: John‬ ‭You might see some C++ programs that runs without the standard namespace‬
‭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‬
‭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:‬
‭Example‬ ‭Example‬

‭28‬ ‭29‬

‭#include <iostream>‬ ‭#include <cmath>‬


‭#include <string>‬ ‭cout << sqrt(64);‬
‭int main() {‬ ‭cout << round(2.6);‬
‭std::string greeting = "Hello";‬ ‭cout << log(2);‬
‭std::cout << greeting;‬ ‭Other Math Functions‬
‭return 0;‬ ‭A list of other popular Math functions (from the <cmath> library) can be found‬
‭}‬ ‭in the table below:‬
‭It is up to you if you want to include the standard namespace library or not.‬

‭C++ Math‬
‭Function‬ ‭Description‬
‭abs(x)‬ ‭Returns the absolute value of x‬
‭acos(x)‬ ‭Returns the arccosine of x‬
‭C++ Math‬
‭asin(x)‬ ‭Returns the arcsine of x‬
‭C++ has many functions that allows you to perform mathematical tasks on‬
‭atan(x)‬ ‭Returns the arctangent of x‬
‭numbers.‬
‭cbrt(x)‬ ‭Returns the cube root of x‬
‭Max and min‬
‭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:‬
‭cos(x)‬ ‭Returns the cosine of x‬
‭Example‬
‭cosh(x)‬ ‭Returns the hyperbolic cosine of x‬
‭cout << max(5, 10);‬
‭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:‬
‭expm1(x)‬ ‭Returns ex -1‬
‭Example‬
‭fabs(x)‬ ‭Returns the absolute value of a floating x‬
‭cout << min(5, 10);‬
‭fdim(x, y)‬ ‭Returns the positive difference between x and y‬
‭C++ <cmath> Header‬
‭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‬
‭hypot(x, y)‬ ‭Returns sqrt(x2 +y2) without intermediate overflow or underflow‬
‭(natural logarithm), can be found in the <cmath> header file:‬
‭fma(x, y, z)‬ ‭Returns x*y+z without losing precision‬
‭Example‬
‭fmax(x, y)‬ ‭Returns the highest value of a floating x and y‬
‭// Include the cmath library‬

‭30‬ ‭31‬
‭fmin(x, y)‬ ‭Returns the lowest value of a floating x and y‬ ‭From the example above, you can read that a true value returns 1, and false‬
‭fmod(x, y)‬ ‭Returns the floating point remainder of x/y‬ ‭returns 0.‬
‭pow(x, y)‬ ‭Returns the value of x to the power of y‬ ‭However, it is more common to return a boolean value by comparing values and‬
‭sin(x)‬ ‭Returns the sine of x (x is in radians)‬ ‭variables .‬
‭sinh(x)‬ ‭Returns the hyperbolic sine of a double value‬
‭tan(x)‬ ‭Returns the tangent of an angle‬ ‭C++ Boolean Expressions‬
‭tanh(x)‬ ‭Returns the hyperbolic tangent of a double value‬
‭Boolean Expression‬

‭C++ Booleans‬ ‭A Boolean expression returns a boolean value that is either 1 (true) or 0 (false).‬
‭This is useful to build logic, and find answers.‬
‭C++ Booleans‬ ‭You can use a comparison operator, such as the greater than (>) operator, to find‬
‭Very often, in programming, you will need a data type that can only have one of‬ ‭out if an expression (or variable) is true or false:‬
‭two values, like:‬ ‭Example‬
‭YES / NO‬ ‭int x = 10;‬
‭ON / OFF‬ ‭int y = 9;‬
‭TRUE / FALSE‬ ‭cout << (x > y); // returns 1 (true), because 10 is higher than 9‬
‭For this, C++ has a bool data type, which can take the values true (1) or false (0).‬ ‭Or even easier:‬
‭Boolean Values‬ ‭Example‬
‭A boolean variable is declared with the bool keyword and can only take the‬ ‭cout << (10 > 9); // returns 1 (true), because 10 is higher than 9‬
‭values true or false:‬ ‭In the examples below, we use the equal to (==) operator to evaluate an‬
‭Example‬ ‭expression:‬
‭bool isCodingFun = true;‬ ‭Example‬
‭bool isFishTasty = false;‬ ‭int x = 10;‬
‭cout << isCodingFun; // Outputs 1 (true)‬ ‭cout << (x == 10); // returns 1 (true), because the value of x is equal to 10‬
‭cout << isFishTasty; // Outputs 0 (false)‬ ‭Example‬
‭cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15‬

‭32‬ ‭33‬

‭Real Life Example‬


‭Let's think of a "real life example" where we need to find out if a person is old‬ ‭C++ If ... Else‬
‭enough to vote.‬
‭C++ Conditions and If Statements‬
‭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‬
‭(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;‬
‭Less than or equal to: a <= b‬
‭int votingAge = 18;‬
‭Greater than: a > b‬
‭cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are‬
‭Greater than or equal to: a >= b‬
‭allowed to vote!‬
‭Equal to a == b‬
‭Cool, right? An even better approach (since we are on a roll now), would be to‬
‭Not Equal to: a != b‬
‭wrap the code above in an if...else statement, so we can perform different‬
‭You can use these conditions to perform different actions for different‬
‭actions depending on the result:‬
‭decisions.‬
‭Example‬
‭C++ has the following conditional statements:‬
‭Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise‬
‭Use if to specify a block of code to be executed, if a specified condition is true‬
‭output "Not old enough to vote.":‬
‭Use else to specify a block of code to be executed, if the same condition is false‬
‭int myAge = 25;‬
‭Use else if to specify a new condition to test, if the first condition is false‬
‭int votingAge = 18;‬
‭Use switch to specify many alternative blocks of code to be executed‬
‭if (myAge >= votingAge) {‬
‭The if Statement‬
‭cout << "Old enough to vote!";‬
‭Use the if statement to specify a block of C++ code to be executed if a condition‬
‭} else {‬
‭is true.‬
‭cout << "Not old enough to vote.";‬
‭Syntax‬
‭}‬
‭if (condition) {‬
‭// Outputs: Old enough to vote!‬
‭// block of code to be executed if the condition is true‬
‭Booleans are the basis for all C++ comparisons and conditions.‬
‭}‬

‭34‬ ‭35‬
‭Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an‬ ‭if (condition) {‬
‭error.‬ ‭// block of code to be executed if the condition is true‬
‭} else {‬
‭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‬
‭if (20 > 18) {‬ ‭int time = 20;‬
‭cout << "20 is greater than 18";‬ ‭if (time < 18) {‬
‭}‬ ‭cout << "Good day.";‬
‭We can also test variables:‬ ‭} else {‬
‭Example‬ ‭cout << "Good evening.";‬
‭int x = 20;‬ ‭}‬
‭int y = 18;‬ ‭// Outputs "Good evening."‬
‭if (x > y) {‬ ‭Example explained‬
‭cout << "x is greater than y";‬ ‭In the example above, time (20) is greater than 18, so the condition is false.‬
‭}‬ ‭Because of this, we move on to the else condition and print to the screen "Good‬
‭Example explained‬ ‭evening". If the time was less than 18, the program would print "Good day".‬
‭In the example above we use two variables, x and y, to test whether x is greater‬ ‭The else if Statement‬
‭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.‬
‭greater than 18, we print to the screen that "x is greater than y".‬ ‭Syntax‬
‭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‬
‭is false.‬ ‭} else if (condition2) {‬
‭// block of code to be executed if the condition1 is false and condition2‬
‭Syntax‬ ‭is true‬

‭36‬ ‭37‬

‭} else {‬ ‭There is also a short-hand if else, which is known as the ternary operator‬
‭// block of code to be executed if the condition1 is false and condition2‬ ‭because it consists of three operands. It can be used to replace multiple lines of‬
‭is false‬ ‭code with a single line. It is often used to replace simple if else statements:‬
‭}‬ ‭Syntax‬
‭Example‬ ‭variable = (condition) ? expressionTrue : expressionFalse;‬
‭int time = 22;‬ ‭Instead of writing:‬
‭if (time < 10) {‬ ‭Example‬
‭cout << "Good morning.";‬ ‭int time = 20;‬
‭} else if (time < 20) {‬ ‭if (time < 18) {‬
‭cout << "Good day.";‬ ‭cout << "Good day.";‬
‭} else {‬ ‭} else {‬
‭cout << "Good evening.";‬ ‭cout << "Good evening.";‬
‭}‬ ‭}‬
‭// Outputs "Good evening."‬ ‭You can simply write:‬
‭Example explained‬ ‭Example‬
‭In the example above, time (22) is greater than 10, so the first condition is false.‬ ‭int time = 20;‬
‭The next condition, in the else if statement, is also false, so we move on to the‬ ‭string result = (time < 18) ? "Good day." : "Good evening.";‬
‭else condition since condition1 and condition2 is both false - and print to the‬ ‭cout << result;‬
‭screen "Good evening".‬
‭However, if the time was 14, our program would print "Good day."‬ ‭C++ Switch‬
‭C++ Short Hand If Else‬ ‭C++ Switch Statements‬
‭Use the switch statement to select one of many code blocks to be executed.‬
‭Short Hand If...Else (Ternary Operator)‬
‭Syntax‬
‭switch(expression) {‬
‭case x:‬

‭38‬ ‭39‬
‭// code block‬ ‭cout << "Wednesday";‬
‭break;‬ ‭break;‬
‭case y:‬ ‭case 4:‬
‭// code block‬ ‭cout << "Thursday";‬
‭break;‬ ‭break;‬
‭default:‬ ‭case 5:‬
‭// code block‬ ‭cout << "Friday";‬
‭}‬ ‭break;‬
‭This is how it works:‬ ‭case 6:‬
‭The switch expression is evaluated once‬ ‭cout << "Saturday";‬
‭The value of the expression is compared with the values of each case‬ ‭break;‬
‭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";‬
‭chapter‬ ‭break;‬
‭The example below uses the weekday number to calculate the weekday name:‬ ‭}‬
‭Example‬ ‭// Outputs "Thursday" (day 4)‬
‭int day = 4;‬ ‭The break Keyword‬
‭switch (day) {‬ ‭When C++ reaches a break keyword, it breaks out of the switch block.‬
‭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.‬
‭case 2:‬ ‭A break can save a lot of execution time because it "ignores" the execution of all‬
‭cout << "Tuesday";‬ ‭the rest of the code in the switch block.‬
‭break;‬
‭case 3:‬ ‭The default Keyword‬

‭40‬ ‭41‬

‭The default keyword specifies some code to run if there is no case match:‬ ‭// code block to be executed‬
‭Example‬ ‭}‬
‭int day = 4;‬ ‭In the example below, the code in the loop will run, over and over again, as long‬
‭switch (day) {‬ ‭as a variable (i) is less than 5:‬
‭case 6:‬ ‭Example‬
‭cout << "Today is Saturday";‬ ‭int i = 0;‬
‭break;‬ ‭while (i < 5) {‬
‭case 7:‬ ‭cout << i << "\n";‬
‭cout << "Today is Sunday";‬ ‭i++;‬
‭break;‬ ‭}‬
‭default:‬ ‭Note: Do not forget to increase the variable used in the condition, otherwise the‬
‭cout << "Looking forward to the Weekend";‬ ‭loop will never end!‬
‭}‬
‭// Outputs "Looking forward to the Weekend"‬ ‭C++ Do/While 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++ Loops‬ ‭block once, before checking if the condition is true, then it will repeat the loop‬
‭Loops can execute a block of code as long as a specified condition is reached.‬ ‭as long as the condition is true.‬
‭Loops are handy because they save time, reduce errors, and they make code‬ ‭Syntax‬
‭more readable.‬ ‭do {‬
‭C++ While Loop‬ ‭// code block to be executed‬
‭The while loop loops through a block of code as long as a specified condition is‬ ‭}‬
‭true:‬ ‭while (condition);‬
‭Syntax‬
‭while (condition) {‬

‭42‬ ‭43‬
‭The example below uses a do/while loop. The loop will always be executed at‬ ‭The example below will print the numbers 0 to 4:‬
‭least once, even if the condition is false, because the code block is executed‬ ‭Example‬
‭before the condition is tested:‬ ‭for (int i = 0; i < 5; i++) {‬
‭Example‬ ‭cout << i << "\n";‬
‭int i = 0;‬ ‭}‬
‭do {‬ ‭Example explained‬
‭cout << i << "\n";‬ ‭Statement 1 sets a variable before the loop starts (int i = 0).‬
‭i++;‬ ‭Statement 2 defines the condition for the loop to run (i must be less than 5). If‬
‭}‬ ‭the condition is true, the loop will start over again, if it is false, the loop will‬
‭while (i < 5);‬ ‭end.‬
‭Do not forget to increase the variable used in the condition, otherwise the loop‬ ‭Statement 3 increases a value (i++) each time the code block in the loop has been‬
‭will never end!‬ ‭executed.‬

‭C++ For Loop‬ ‭Another Example‬


‭This example will only print even values between 0 and 10:‬
‭C++ For Loop‬
‭Example‬
‭When you know exactly how many times you want to loop through a block of‬
‭for (int i = 0; i <= 10; i = i + 2) {‬
‭code, use the for loop instead of a while loop:‬
‭cout << i << "\n";‬
‭Syntax‬
‭}‬
‭for (statement 1; statement 2; statement 3) {‬
‭Nested Loops‬
‭// code block to be executed‬
‭It is also possible to place a loop inside another loop. This is called a nested‬
‭}‬
‭loop.‬
‭Statement 1 is executed (one time) before the execution of the code block.‬
‭The "inner loop" will be executed one time for each iteration of the "outer‬
‭Statement 2 defines the condition for executing the code block.‬
‭loop":‬
‭Statement 3 is executed (every time) after the code block has been executed.‬
‭Example‬

‭44‬ ‭45‬

‭// Outer loop‬ ‭You have already seen the break statement used in an earlier chapter of this‬
‭for (int i = 1; i <= 2; ++i) {‬ ‭tutorial. It was used to "jump out" of a switch statement.‬
‭cout << "Outer: " << i << "\n"; // Executes 2 times‬ ‭The break statement can also be used to jump out of a loop.‬
‭// Inner loop‬ ‭This example jumps out of the loop when i is equal to 4:‬
‭for (int j = 1; j <= 3; ++j) {‬ ‭Example‬
‭cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)‬ ‭for (int i = 0; i < 10; i++) {‬
‭}‬ ‭if (i == 4) {‬
‭}‬ ‭break;‬
‭The foreach Loop‬ ‭}‬
‭There is also a "for-each loop" (introduced in C++ version 11 (2011), which is‬ ‭cout << i << "\n";‬
‭used exclusively to loop through elements in an array (or other data sets):‬ ‭}‬
‭Syntax‬ ‭C++ Continue‬
‭for (type variableName : arrayName) {‬ ‭The continue statement breaks one iteration (in the loop), if a specified‬
‭// code block to be executed‬ ‭condition occurs, and continues with the next iteration in the loop.‬
‭}‬ ‭This example skips the value of 4:‬
‭The following example outputs all elements in an array, using a "for-each loop":‬ ‭Example‬
‭Example‬ ‭for (int i = 0; i < 10; i++) {‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬ ‭if (i == 4) {‬
‭for (int i : myNumbers) {‬ ‭continue;‬
‭cout << i << "\n";‬ ‭}‬
‭}‬ ‭cout << i << "\n";‬

‭C++ Break and Continue‬


‭}‬
‭Break and Continue in While Loop‬
‭You can also use break and continue in while loops:‬
‭C++ Break‬
‭Break Example‬

‭46‬ ‭47‬
‭int i = 0;‬ ‭string cars[4];‬
‭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‬
‭i++;‬ ‭list, inside curly braces:‬
‭if (i == 4) {‬ ‭string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};‬
‭break;‬ ‭To create an array of three integers, you could write:‬
‭}‬ ‭int myNum[3] = {10, 20, 30};‬
‭}‬ ‭Access the Elements of an Array‬
‭Continue Example‬ ‭You access an array element by referring to the index number inside square‬
‭int i = 0;‬ ‭brackets [].‬
‭while (i < 10) {‬ ‭This statement accesses the value of the first element in cars:‬
‭if (i == 4) {‬ ‭Example‬
‭i++;‬ ‭string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};‬
‭continue;‬ ‭cout << cars[0];‬
‭}‬ ‭// Outputs Volvo‬
‭cout << i << "\n";‬ ‭Note: Array indexes start with 0: [0] is the first element. [1] is the second‬
‭i++;‬ ‭element, etc.‬
‭}‬

‭C++ Arrays‬
‭Change an Array Element‬
‭To change the value of a specific element, refer to the index number:‬
‭cars[0] = "Opel";‬
‭C++ Arrays‬
‭Example‬
‭Arrays are used to store multiple values in a single variable, instead of declaring‬
‭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‬
‭cout << cars[0];‬
‭followed by square brackets and specify the number of elements it should store:‬

‭48‬ ‭49‬

‭// Now outputs Opel instead of Volvo‬ ‭There is also a "for-each loop" (introduced in C++ version 11 (2011), which is‬

‭C++ Arrays and Loops‬


‭used exclusively to loop through elements in an array:‬
‭Syntax‬
‭for (type variableName : arrayName) {‬
‭Loop Through an Array‬
‭// code block to be executed‬
‭You can loop through the array elements with the for loop.‬
‭}‬
‭The following example outputs all elements in the cars array:‬
‭The following example outputs all elements in an array, using a "for-each loop":‬
‭Example‬
‭Example‬
‭string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭for (int i = 0; i < 5; i++) {‬
‭for (int i : myNumbers) {‬
‭cout << cars[i] << "\n";‬
‭cout << i << "\n";‬
‭}‬
‭}‬
‭This example outputs the index of each element together with its value:‬
‭Example‬
‭string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};‬
‭C++ Omit Array Size‬
‭for (int i = 0; i < 5; i++) {‬ ‭Omit Array Size‬
‭cout << i << " = " << cars[i] << "\n";‬ ‭In C++, you don't have to specify the size of the array. The compiler is smart‬
‭}‬ ‭enough to determine the size of the array based on the number of inserted‬
‭And this example shows how to loop through an array of integers:‬ ‭values:‬
‭Example‬ ‭string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬ ‭The example above is equal to:‬
‭for (int i = 0; i < 5; i++) {‬ ‭string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements‬
‭cout << myNumbers[i] << "\n";‬ ‭However, the last approach is considered as "good practice", because it will‬
‭}‬ ‭reduce the chance of errors in your program.‬
‭The foreach Loop‬ ‭Omit Elements on Declaration‬

‭50‬ ‭51‬
‭It is also possible to declare an array without specifying the elements on‬ ‭Loop Through an Array with sizeof()‬
‭declaration, and add them later:‬ ‭In the Arrays and Loops Chapter, we wrote the size of the array in the loop‬
‭Example‬ ‭condition (i < 5). This is not ideal, since it will only work for arrays of a specified‬
‭string cars[5];‬ ‭size.‬
‭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.‬

‭C++ Array Size‬


‭Instead of writing:‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭for (int i = 0; i < 5; i++) {‬
‭Get the Size of an Array‬
‭cout << myNumbers[i] << "\n";‬
‭To get the size of an array, you can use the sizeof() operator:‬
‭}‬
‭Example‬
‭It is better to write:‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭Example‬
‭cout << sizeof(myNumbers);‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭Result: 20‬
‭for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {‬
‭Why did the result show 20 instead of 5, when the array contains 5 elements?‬
‭cout << myNumbers[i] << "\n";‬
‭It is because the sizeof() operator returns the size of a type in bytes.‬
‭}‬
‭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:‬
‭from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.‬
‭Example‬
‭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};‬
‭array by the size of the data type it contains:‬
‭for (int i : myNumbers) {‬
‭Example‬
‭cout << i << "\n";‬
‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭}‬
‭int getArrayLength = sizeof(myNumbers) / sizeof(int);‬
‭It is good to know the different ways to loop through an array, since you may‬
‭cout << getArrayLength;‬
‭encounter them all in different programs.‬
‭Result: 5‬

‭52‬ ‭53‬

‭C++ Multi-Dimensional Arrays‬


‭{‬
‭{ "E", "F" },‬
‭{ "G", "H" }‬
‭Multi-Dimensional Arrays‬
‭}‬
‭A multi-dimensional array is an array of arrays.‬
‭};‬
‭To declare a multi-dimensional array, define the variable type, specify the name‬
‭Access the Elements of a Multi-Dimensional Array‬
‭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‬
‭main array has, followed by another set of square brackets which indicates how‬
‭each of the array's dimensions.‬
‭many elements the sub-arrays have:‬
‭This statement accesses the value of the element in the first row (0) and third‬
‭string letters[2][4];‬
‭column (2) of the letters array.‬
‭As with ordinary arrays, you can insert values with an array literal - a‬
‭Example‬
‭comma-separated list inside curly braces. In a multi-dimensional array, each‬
‭string letters[2][4] = {‬
‭element in an array literal is another array literal.‬
‭{ "A", "B", "C", "D" },‬
‭string letters[2][4] = {‬
‭{ "E", "F", "G", "H" }‬
‭{ "A", "B", "C", "D" },‬
‭};‬
‭{ "E", "F", "G", "H" }‬
‭cout << letters[0][2]; // Outputs "C"‬
‭};‬
‭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.‬
‭Arrays can have any number of dimensions. The more dimensions an array has,‬
‭Change Elements in a Multi-Dimensional Array‬
‭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] = {‬
‭each of the dimensions:‬
‭{‬
‭Example‬
‭{ "A", "B" },‬
‭string letters[2][4] = {‬
‭{ "C", "D" }‬
‭{ "A", "B", "C", "D" },‬
‭},‬

‭54‬ ‭55‬
‭{ "E", "F", "G", "H" }‬ ‭{‬
‭};‬ ‭{ "E", "F" },‬
‭letters[0][0] = "Z";‬ ‭{ "G", "H" }‬
‭cout << letters[0][0]; // Now outputs "Z" instead of "A"‬ ‭}‬
‭Loop Through a Multi-Dimensional Array‬ ‭};‬
‭To loop through a multi-dimensional array, you need one loop for each of the‬ ‭for (int i = 0; i < 2; i++) {‬
‭array's dimensions.‬ ‭for (int j = 0; j < 2; j++) {‬
‭The following example outputs all elements in the letters array:‬ ‭for (int k = 0; k < 2; k++) {‬
‭Example‬ ‭cout << letters[i][j][k] << "\n";‬
‭string letters[2][4] = {‬ ‭}‬
‭{ "A", "B", "C", "D" },‬ ‭}‬
‭{ "E", "F", "G", "H" }‬ ‭}‬
‭};‬ ‭Why Multi-Dimensional Arrays?‬
‭for (int i = 0; i < 2; i++) {‬ ‭Multi-dimensional arrays are great at representing grids. This example shows a‬
‭for (int j = 0; j < 4; j++) {‬ ‭practical use for them. In the following example we use a multi-dimensional‬
‭cout << letters[i][j] << "\n";‬ ‭array to represent a small game of Battleship:‬
‭}‬ ‭Example‬
‭}‬ ‭// We put "1" to indicate there is a ship.‬
‭This example shows how to loop through a three-dimensional array:‬ ‭bool ships[4][4] = {‬
‭Example‬ ‭{ 0, 1, 1, 0 },‬
‭string letters[2][2][2] = {‬ ‭{ 0, 0, 0, 0 },‬
‭{‬ ‭{ 0, 0, 1, 0 },‬
‭{ "A", "B" },‬ ‭{ 0, 0, 1, 0 }‬
‭{ "C", "D" }‬ ‭};‬
‭},‬

‭56‬ ‭57‬

‭// Keep track of how many hits the player has and how many turns they‬ ‭}‬
‭have played in these variables‬ ‭// Count how many turns the player has taken‬
‭int hits = 0;‬ ‭numberOfTurns++;‬
‭int numberOfTurns = 0;‬ ‭}‬
‭// Allow the player to keep going until they have hit all four ships‬ ‭cout << "Victory!\n";‬
‭while (hits < 4) {‬ ‭cout << "You won in " << numberOfTurns << " turns";‬
‭int row, column;‬
‭cout << "Selecting coordinates\n";‬ ‭C++ Structures (struct)‬
‭// 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,‬
‭cout << "Choose a column number between 0 and 3: ";‬
‭bool, etc.).‬
‭cin >> column;‬
‭Create a Structure‬
‭// Check if a ship exists in those coordinates‬
‭To create a structure, use the struct keyword and declare each of its members‬
‭if (ships[row][column]) {‬
‭inside curly braces.‬
‭// 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‬
‭ships[row][column] = 0;‬
‭the example below):‬
‭// Increase the hit counter‬
‭struct { // Structure declaration‬
‭hits++;‬
‭int myNum; // Member (int variable)‬
‭// Tell the player that they have hit a ship and how many ships are left‬
‭string myString; // Member (string variable)‬
‭cout << "Hit! " << (4-hits) << " left.\n\n";‬
‭} myStructure; // Structure variable‬
‭} 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‬

‭58‬ ‭59‬
‭Assign data to members of a structure and print it:‬ ‭string model;‬
‭// Create a structure variable called myStructure‬ ‭int year;‬
‭struct {‬ ‭} myCar1, myCar2; // We can add variables by separating them with a‬
‭int myNum;‬ ‭comma here‬
‭string myString;‬ ‭// Put data into the first structure‬
‭} myStructure;‬ ‭myCar1.brand = "BMW";‬
‭// Assign values to members of myStructure‬ ‭myCar1.model = "X5";‬
‭myStructure.myNum = 1;‬ ‭myCar1.year = 1999;‬
‭myStructure.myString = "Hello World!";‬ ‭// Put data into the second structure‬
‭// Print members of myStructure‬ ‭myCar2.brand = "Ford";‬
‭cout << myStructure.myNum << "\n";‬ ‭myCar2.model = "Mustang";‬
‭cout << myStructure.myString << "\n";‬ ‭myCar2.year = 1969;‬
‭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 <<‬
‭struct {‬ ‭"\n";‬
‭int myNum;‬ ‭cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<‬
‭string myString;‬ ‭"\n";‬
‭} myStruct1, myStruct2, myStruct3; // Multiple structure variables‬ ‭Named Structures‬
‭separated with‬ ‭By giving a name to the structure, you can treat it as a data type. This means‬
‭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.‬
‭Example‬ ‭To create a named structure, put the name of the structure right after the struct‬
‭Use one structure to represent two cars:‬ ‭keyword:‬
‭struct {‬ ‭struct myDataType { // This structure is named "myDataType"‬
‭string brand;‬ ‭int myNum;‬

‭60‬ ‭61‬

‭string myString;‬ ‭// Print the structure members‬


‭};‬ ‭cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year <<‬
‭To declare a variable that uses the structure, use the name of the structure as the‬ ‭"\n";‬
‭data type of the variable:‬ ‭cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year <<‬
‭myDataType myVar;‬ ‭"\n";‬
‭Example‬ ‭return 0;‬
‭Use one structure to represent two cars:‬ ‭}‬
‭// Declare a structure named "car"‬
‭struct car {‬ ‭C++ References‬
‭string brand;‬
‭Creating References‬
‭string model;‬
‭A reference variable is a "reference" to an existing variable, and it is created‬
‭int year;‬
‭with the & operator:‬
‭};‬
‭string food = "Pizza"; // food variable‬
‭int main() {‬
‭string &meal = food; // reference to food‬
‭// Create a car structure and store it in myCar1;‬
‭Now, we can use either the variable name food or the reference name meal to‬
‭car myCar1;‬
‭refer to the food variable:‬
‭myCar1.brand = "BMW";‬
‭Example‬
‭myCar1.model = "X5";‬
‭string food = "Pizza";‬
‭myCar1.year = 1999;‬
‭string &meal = food;‬
‭cout << food << "\n"; // Outputs Pizza‬
‭// Create another car structure and store it in myCar2;‬
‭cout << meal << "\n"; // Outputs Pizza‬
‭car myCar2;‬
‭myCar2.brand = "Ford";‬
‭myCar2.model = "Mustang";‬
‭myCar2.year = 1969;‬ ‭C++ Memory Address‬
‭62‬ ‭63‬
‭Memory Address‬ ‭string food = "Pizza"; // A food variable of type string‬
‭In the example from the previous page, the & operator was used to create a‬ ‭cout << food; // Outputs the value of food (Pizza)‬
‭reference variable. But it can also be used to get the memory address of a‬ ‭cout << &food; // Outputs the memory address of food (0x6dfed4)‬
‭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.‬
‭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‬
‭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:‬
‭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‬
‭cout << &food; // Outputs 0x6dfed4‬ ‭the address of food‬
‭Note: The memory address is in hexadecimal form (0x..). Note that you may not‬ ‭// Output the value of food (Pizza)‬
‭get the same result in your program.‬ ‭cout << food << "\n";‬
‭And why is it useful to know the memory address?‬ ‭// Output the memory address of food (0x6dfed4)‬
‭References and Pointers (which you will learn about in the next chapter) are‬ ‭cout << &food << "\n";‬
‭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)‬
‭computer's memory - which can reduce the code and improve the performance.‬ ‭cout << ptr << "\n";‬
‭These two features are one of the things that make C++ stand out from other‬ ‭Example explained‬
‭programming languages, like Python and Java.‬ ‭Create a pointer variable with the name ptr, that points to a string variable, by‬

‭C++ Pointers‬
‭using the asterisk sign * (string* ptr). Note that the type of the pointer has to‬
‭match the type of the variable you're working with.‬
‭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.‬
‭variable by using the & operator:‬
‭Example‬

‭64‬ ‭65‬

‭Tip: There are three ways to declare pointer variables, but the first way is‬
‭preferred:‬ ‭C++ Modify Pointers‬
‭Modify the Pointer Value‬
‭string* mystring; // Preferred‬
‭You can also change the pointer's value. But note that this will also change the‬
‭string *mystring;‬
‭value of the original variable:‬
‭string * mystring;‬
‭Example‬

‭C++ Dereference‬ ‭string food = "Pizza";‬


‭string* ptr = &food;‬
‭Get Memory Address and Value‬ ‭// Output the value of food (Pizza)‬
‭In the example from the previous page, we used the pointer variable to get the‬ ‭cout << food << "\n";‬
‭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";‬
‭the * operator (the dereference operator):‬ ‭// Access the memory address of food and output its value (Pizza)‬
‭Example‬ ‭cout << *ptr << "\n";‬
‭string food = "Pizza"; // Variable declaration‬ ‭// Change the value of the pointer‬
‭string* ptr = &food; // Pointer declaration‬ ‭*ptr = "Hamburger";‬
‭// Reference: Output the memory address of food with the pointer‬ ‭// Output the new value of the pointer (Hamburger)‬
‭(0x6dfed4)‬ ‭cout << *ptr << "\n";‬
‭cout << ptr << "\n";‬ ‭// Output the new value of the food variable (Hamburger)‬
‭// Dereference: Output the value of food with the pointer (Pizza)‬ ‭cout << food << "\n";‬
‭cout << *ptr << "\n";‬
‭Note that the * sign can be confusing here, as it does two different things in our‬ ‭C++ Functions‬
‭code:‬
‭A function is a block of code which only runs when it is called.‬
‭When used in declaration (string* ptr), it creates a pointer variable.‬
‭You can pass data, known as parameters, into a function.‬
‭When not used in declaration, it act as a dereference operator.‬

‭66‬ ‭67‬
‭Functions are used to perform certain actions, and they are important for‬ ‭Inside main, call myFunction():‬
‭reusing code: Define the code once, and use it many times.‬ ‭// Create a function‬
‭Create a Function‬ ‭void myFunction() {‬
‭C++ provides some pre-defined functions, such as main(), which is used to‬ ‭cout << "I just got executed!";‬
‭execute code. But you can also create your own functions to perform certain‬ ‭}‬
‭actions.‬ ‭int main() {‬
‭To create (often referred to as declare) a function, specify the name of the‬ ‭myFunction(); // call the function‬
‭function, followed by parentheses ():‬ ‭return 0;‬
‭Syntax‬ ‭}‬
‭void myFunction() {‬ ‭// Outputs "I just got executed!"‬
‭// code to be executed‬ ‭A function can be called multiple times:‬
‭}‬ ‭Example‬
‭Example Explained‬ ‭void myFunction() {‬
‭myFunction() is the name of the function‬ ‭cout << "I just got executed!\n";‬
‭void means that the function does not have a return value. You will learn more‬ ‭}‬
‭about return values later in the next chapter‬ ‭int main() {‬
‭inside the function (the body), add code that defines what the function should do‬ ‭myFunction();‬
‭Call a Function‬ ‭myFunction();‬
‭Declared functions are not executed immediately. They are "saved for later use",‬ ‭myFunction();‬
‭and will be executed later, when they are called.‬ ‭return 0;‬
‭To call a function, write the function's name followed by two parentheses () and‬ ‭}‬
‭a semicolon ;‬ ‭// I just got executed!‬
‭In the following example, myFunction() is used to print a text (the action), when‬ ‭// I just got executed!‬
‭it is called:‬ ‭// I just got executed!‬
‭Example‬ ‭Function Declaration and Definition‬

‭68‬ ‭69‬

‭A C++ function consist of two parts:‬


‭Declaration: the return type, the name of the function, and parameters (if any)‬ ‭// The main method‬
‭Definition: the body of the function (code to be executed)‬ ‭int main() {‬
‭void myFunction() { // declaration‬ ‭myFunction(); // call the function‬
‭// the body of the function (definition)‬ ‭return 0;‬
‭}‬ ‭}‬
‭Note: If a user-defined function, such as myFunction() is declared after the‬
‭main() function, an error will occur:‬ ‭// Function definition‬
‭Example‬ ‭void myFunction() {‬
‭int main() {‬ ‭cout << "I just got executed!";‬
‭myFunction();‬ ‭}‬
‭return 0;‬
‭}‬ ‭C++ Function Parameters‬
‭void myFunction() {‬
‭Parameters and Arguments‬
‭cout << "I just got executed!";‬
‭Information can be passed to functions as a parameter. Parameters act as‬
‭}‬
‭variables inside the function.‬
‭// Error‬
‭Parameters are specified after the function name, inside the parentheses. You‬
‭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:‬
‭function - for code optimization.‬
‭Syntax‬
‭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‬
‭and easier to read:‬
‭}‬
‭Example‬
‭The following example has a function that takes a string called fname as‬
‭// Function declaration‬
‭parameter. When the function is called, we pass along a first name, which is‬
‭void myFunction();‬
‭used inside the function to print the full name:‬

‭70‬ ‭71‬
‭Example‬ ‭int main() {‬
‭void myFunction(string fname) {‬ ‭myFunction("Sweden");‬
‭cout << fname << " Refsnes\n";‬ ‭myFunction("India");‬
‭}‬ ‭myFunction();‬
‭int main() {‬ ‭myFunction("USA");‬
‭myFunction("Liam");‬ ‭return 0;‬
‭myFunction("Jenny");‬ ‭}‬
‭myFunction("Anja");‬ ‭// Sweden‬
‭return 0;‬ ‭// India‬
‭}‬ ‭// Norway‬
‭// Liam Refsnes‬ ‭// USA‬
‭// Jenny Refsnes‬ ‭A parameter with a default value, is often known as an "optional parameter".‬
‭// Anja Refsnes‬ ‭From the example above, country is an optional parameter and "Norway" is the‬
‭When a parameter is passed to the function, it is called an argument. So, from‬ ‭default value.‬
‭the example above: fname is a parameter, while Liam, Jenny and Anja are‬
‭arguments.‬ ‭C++ Multiple Parameters‬
‭C++ Default Parameters‬ ‭Multiple Parameters‬
‭Inside the function, you can add as many parameters as you want:‬

‭Default Parameter Value‬ ‭Example‬

‭You can also use a default parameter value, by using the equals sign (=).‬ ‭void myFunction(string fname, int age) {‬

‭If we call the function without an argument, it uses the default value ("Norway"):‬ ‭cout << fname << " Refsnes. " << age << " years old. \n";‬

‭Example‬ ‭}‬

‭void myFunction(string country = "Norway") {‬ ‭int main() {‬

‭cout << country << "\n";‬ ‭myFunction("Liam", 3);‬

‭}‬ ‭myFunction("Jenny", 14);‬

‭72‬ ‭73‬

‭myFunction("Anja", 30);‬ ‭// Outputs 8 (5 + 3)‬


‭return 0;‬ ‭This example returns the sum of a function with two parameters:‬
‭}‬ ‭Example‬
‭// Liam Refsnes. 3 years old.‬ ‭int myFunction(int x, int y) {‬
‭// Jenny Refsnes. 14 years old.‬ ‭return x + y;‬
‭// Anja Refsnes. 30 years old.‬ ‭}‬
‭Note that when you are working with multiple parameters, the function call‬ ‭int main() {‬
‭must have the same number of arguments as there are parameters, and the‬ ‭cout << myFunction(5, 3);‬
‭arguments must be passed in the same order.‬ ‭return 0;‬
‭}‬

‭C++ The Return Keyword‬


‭// Outputs 8 (5 + 3)‬
‭You can also store the result in a variable:‬
‭Example‬
‭Return Values‬
‭int myFunction(int x, int y) {‬
‭The void keyword, used in the previous examples, indicates that the function‬
‭return x + y;‬
‭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‬
‭int main() {‬
‭inside the function:‬
‭int z = myFunction(5, 3);‬
‭Example‬
‭cout << z;‬
‭int myFunction(int x) {‬
‭return 0;‬
‭return 5 + x;‬
‭}‬
‭}‬
‭// Outputs 8 (5 + 3)‬
‭int main() {‬
‭cout << myFunction(3);‬
‭return 0;‬
‭C++ Functions - Pass By Reference‬
‭}‬

‭74‬ ‭75‬
‭Pass By Reference‬ ‭Pass Arrays as Function Parameters‬
‭In the examples from the previous page, we used normal variables when we‬ ‭You can also pass arrays to a function:‬
‭passed parameters to a function. You can also pass a reference to the function.‬ ‭Example‬
‭This can be useful when you need to change the value of the arguments:‬ ‭void myFunction(int myNumbers[5]) {‬
‭Example‬ ‭for (int i = 0; i < 5; i++) {‬
‭void swapNums(int &x, int &y) {‬ ‭cout << myNumbers[i] << "\n";‬
‭int z = x;‬ ‭}‬
‭x = y;‬ ‭}‬
‭y = z;‬ ‭int main() {‬
‭}‬ ‭int myNumbers[5] = {10, 20, 30, 40, 50};‬
‭int main() {‬ ‭myFunction(myNumbers);‬
‭int firstNum = 10;‬ ‭return 0;‬
‭int secondNum = 20;‬ ‭}‬
‭cout << "Before swap: " << "\n";‬ ‭Example Explained‬
‭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.‬
‭secondNum‬
‭swapNums(firstNum, secondNum);‬ ‭When the function is called inside main(), we pass along the myNumbers array,‬
‭cout << "After swap: " << "\n";‬ ‭which outputs the array elements.‬
‭cout << firstNum << secondNum << "\n";‬
‭return 0;‬ ‭Note that when you call the function, you only need to use the name of the array‬
‭}‬ ‭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++ Pass Array to a Function‬


‭76‬ ‭77‬

‭C++ Function Overloading‬


‭Instead of defining two functions that should do the same thing, it is better to‬
‭overload one.‬
‭In the example below, we overload the plusFunc function to work for both int‬
‭Function Overloading‬
‭and double:‬
‭With function overloading, multiple functions can have the same name with‬
‭Example‬
‭different parameters:‬
‭int plusFunc(int x, int y) {‬
‭Example‬
‭return x + y;‬
‭int myFunction(int x)‬
‭}‬
‭float myFunction(float x)‬
‭double plusFunc(double x, double y) {‬
‭double myFunction(double x, double y)‬
‭return x + y;‬
‭Consider the following example, which have two functions that add‬
‭}‬
‭numbers of different type:‬
‭int main() {‬
‭Example‬
‭int myNum1 = plusFunc(8, 5);‬
‭int plusFuncInt(int x, int y) {‬
‭double myNum2 = plusFunc(4.3, 6.26);‬
‭return x + y;‬
‭cout << "Int: " << myNum1 << "\n";‬
‭}‬
‭cout << "Double: " << myNum2;‬
‭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() {‬
‭type of parameters are different.‬
‭int myNum1 = plusFuncInt(8, 5);‬
‭double myNum2 = plusFuncDouble(4.3, 6.26);‬
‭cout << "Int: " << myNum1 << "\n";‬
‭cout << "Double: " << myNum2;‬
‭C++ Recursion‬
‭return 0;‬ ‭Recursion‬
‭}‬

‭78‬ ‭79‬
‭Recursion is the technique of making a function call itself. This technique‬ ‭When the sum() function is called, it adds parameter k to the sum of all numbers‬
‭provides a way to break complicated problems down into simple problems‬ ‭smaller than k and returns the result. When k becomes 0, the function just‬
‭which are easier to solve.‬ ‭returns 0. When running, the program follows these steps:‬
‭Recursion may be a bit difficult to understand. The best way to figure out how it‬
‭works is to experiment with it.‬ ‭10 + sum(9)‬
‭Recursion Example‬ ‭10 + ( 9 + sum(8) )‬
‭Adding two numbers together is easy to do, but adding a range of numbers is‬ ‭10 + ( 9 + ( 8 + sum(7) ) )‬
‭more complicated. In the following example, recursion is used to add a range of‬ ‭...‬
‭numbers together by breaking it down into the simple task of adding two‬ ‭10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)‬
‭numbers:‬ ‭10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0‬
‭Example‬ ‭Since the function does not call itself when k is 0, the program stops there and‬
‭int sum(int k) {‬ ‭returns the result.‬
‭if (k > 0) {‬ ‭The developer should be very careful with recursion as it can be quite easy to‬
‭return k + sum(k - 1);‬ ‭slip into writing a function which never terminates, or one that uses excess‬
‭} else {‬ ‭amounts of memory or processor power. However, when written correctly‬
‭return 0;‬ ‭recursion can be a very efficient and mathematically-elegant approach to‬
‭}‬ ‭programming.‬
‭}‬
‭int main() {‬
‭int result = sum(10);‬ ‭C++ OOP‬
‭cout << result;‬
‭C++ What is OOP?‬
‭return 0;‬
‭OOP stands for Object-Oriented Programming.‬
‭}‬
‭Example Explained‬

‭80‬ ‭81‬

‭Procedural programming is about writing procedures or functions that perform‬ ‭Objects‬


‭operations on the data, while object-oriented programming is about creating‬ ‭Apple‬
‭objects that contain both data and functions.‬ ‭Banana‬
‭Mango‬
‭Object-oriented programming has several advantages over procedural‬
‭programming:‬ ‭Another example:‬

‭OOP is faster and easier to execute‬ ‭Class‬


‭OOP provides a clear structure for the programs‬ ‭Car‬
‭OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the‬ ‭Objects‬
‭code easier to maintain, modify and debug‬ ‭Volvo‬
‭OOP makes it possible to create full reusable applications with less code and‬ ‭Audi‬
‭shorter development time‬ ‭Toyota‬
‭Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the‬
‭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.‬
‭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‬
‭repeating it.‬ ‭functions from the class.‬
‭You will learn much more about classes and objects in the next chapter.‬
‭C++ What are Classes and Objects?‬
‭Classes and objects are the two main aspects of object-oriented programming.‬
‭Look at the following illustration to see the difference between class and‬ ‭C++ Classes and Objects‬
‭objects:‬
‭C++ Classes/Objects‬
‭class‬
‭C++ is an object-oriented programming language.‬
‭Fruit‬

‭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‬
‭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.‬
‭attributes, such as weight and color, and methods, such as drive and brake.‬ ‭At last, end the class definition with a semicolon ;.‬
‭Create an Object‬
‭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‬
‭class. These are often referred to as "class members".‬ ‭named MyClass, so now we can use this to create 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‬
‭as an object constructor, or a "blueprint" for creating objects.‬ ‭name.‬

‭Create a Class‬ ‭To access the class attributes (myNum and myString), use the dot syntax (.) on‬
‭To create a class, use the class keyword:‬ ‭the object:‬
‭Example‬
‭Create a class called "MyClass":‬ ‭Example‬
‭Create an object called "myObj" and access the attributes:‬
‭class MyClass { // The class‬
‭public: // Access specifier‬ ‭class MyClass { // The class‬
‭int myNum; // Attribute (int variable)‬ ‭public: // Access specifier‬
‭string myString; // Attribute (string variable)‬ ‭int myNum; // Attribute (int variable)‬
‭};‬ ‭string myString; // Attribute (string variable)‬
‭Example explained‬ ‭};‬
‭The class keyword is used to create a class called MyClass.‬ ‭int main() {‬
‭The public keyword is an access specifier, which specifies that members‬ ‭MyClass myObj; // Create an object of MyClass‬
‭(attributes and methods) of the class are accessible from outside the class. You‬ ‭// Access attributes and set values‬
‭will learn more about access specifiers later.‬ ‭myObj.myNum = 15;‬

‭84‬ ‭85‬

‭myObj.myString = "Some text";‬ ‭carObj2.brand = "Ford";‬


‭// Print attribute values‬ ‭carObj2.model = "Mustang";‬
‭cout << myObj.myNum << "\n";‬ ‭carObj2.year = 1969;‬
‭cout << myObj.myString;‬ ‭// Print attribute values‬
‭return 0;‬ ‭cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<‬
‭}‬ ‭"\n";‬
‭Multiple Objects‬ ‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬
‭You can create multiple objects of one class:‬ ‭"\n";‬
‭return 0;‬
‭Example‬ ‭}‬
‭// Create a Car class with some attributes‬
‭class Car {‬
‭public:‬ ‭C++ Class Methods‬
‭string brand;‬
‭Class Methods‬
‭string model;‬
‭Methods are functions that belongs to the class.‬
‭int year;‬
‭There are two ways to define functions that belongs to a class:‬
‭};‬
‭Inside class definition‬
‭int main() {‬
‭Outside class definition‬
‭// Create an object of Car‬
‭In the following example, we define a function inside the class, and we name it‬
‭Car carObj1;‬
‭"myMethod".‬
‭carObj1.brand = "BMW";‬
‭Note: You access methods just like you access attributes; by creating an object‬
‭carObj1.model = "X5";‬
‭of the class and using the dot syntax (.):‬
‭carObj1.year = 1999;‬
‭Inside Example‬
‭// Create another object of Car‬
‭class MyClass { // The class‬
‭Car carObj2;‬
‭public: // Access specifier‬

‭86‬ ‭87‬
‭void myMethod() { // Method/function defined inside the class‬ ‭myObj.myMethod(); // Call the method‬
‭cout << "Hello World!";‬ ‭return 0;‬
‭}‬ ‭}‬
‭};‬ ‭Parameters‬
‭int main() {‬ ‭You can also add parameters:‬
‭MyClass myObj; // Create an object of MyClass‬ ‭Example‬
‭myObj.myMethod(); // Call the method‬ ‭#include <iostream>‬
‭return 0;‬ ‭using namespace std;‬
‭}‬ ‭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);‬
‭name of the class, followed the scope resolution :: operator, followed by the‬ ‭};‬
‭name of the function:‬ ‭int Car::speed(int maxSpeed) {‬
‭return maxSpeed;‬
‭Outside Example‬ ‭}‬
‭class MyClass { // The class‬ ‭int main() {‬
‭public: // Access specifier‬ ‭Car myObj; // Create an object of Car‬
‭void myMethod(); // Method/function declaration‬ ‭cout << myObj.speed(200); // Call the method with an argument‬
‭};‬ ‭return 0;‬
‭// Method/function definition outside the class‬ ‭}‬
‭void MyClass::myMethod() {‬
‭cout << "Hello World!";‬
‭}‬ ‭C++ Constructors‬
‭int main() {‬
‭Constructors‬
‭MyClass myObj; // Create an object of MyClass‬

‭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‬
‭object of a class is created.‬ ‭with different parameters. Inside the constructor we set the attributes equal to‬
‭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‬
‭():‬ ‭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:‬
‭class MyClass { // The class‬
‭public: // Access specifier‬ ‭Example‬
‭MyClass() { // Constructor‬ ‭class Car { // The class‬
‭cout << "Hello World!";‬ ‭public: // Access specifier‬
‭}‬ ‭string brand; // Attribute‬
‭};‬ ‭string model; // Attribute‬
‭int main() {‬ ‭int year; // Attribute‬
‭MyClass myObj; // Create an object of MyClass (this will call the‬ ‭Car(string x, string y, int z) { // Constructor with parameters‬
‭constructor)‬ ‭brand = x;‬
‭return 0;‬ ‭model = y;‬
‭}‬ ‭year = z;‬
‭Note: The constructor has the same name as the class, it is always public, and it‬ ‭}‬
‭does not have any return value.‬ ‭};‬
‭int main() {‬

‭Constructor Parameters‬
‭// Create Car objects and call the constructor with different values‬
‭Car carObj1("BMW", "X5", 1999);‬
‭Car carObj2("Ford", "Mustang", 1969);‬
‭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 <<‬
‭"\n";‬

‭90‬ ‭91‬
‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬ ‭Car carObj1("BMW", "X5", 1999);‬
‭"\n";‬ ‭Car carObj2("Ford", "Mustang", 1969);‬
‭return 0;‬ ‭// Print values‬
‭}‬ ‭cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year <<‬
‭Just like functions, constructors can also be defined outside the class. First,‬ ‭"\n";‬
‭declare the constructor inside the class, and then define it outside of the class by‬ ‭cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year <<‬
‭specifying the name of the class, followed by the scope resolution :: operator,‬ ‭"\n";‬
‭followed by the name of the constructor (which is the same as the class):‬ ‭return 0;‬
‭}‬
‭Example‬
‭class Car { // The class‬
‭public: // Access specifier‬ ‭C++ Access Specifiers‬
‭string brand; // Attribute‬
‭Access Specifiers‬
‭string model; // Attribute‬
‭By now, you are quite familiar with the public keyword that appears in all of our‬
‭int year; // Attribute‬
‭class examples:‬
‭Car(string x, string y, int z); // Constructor declaration‬
‭Example‬
‭};‬
‭class MyClass { // The class‬
‭// Constructor definition outside the class‬
‭public: // Access specifier‬
‭Car::Car(string x, string y, int z) {‬
‭// class members goes here‬
‭brand = x;‬
‭};‬
‭model = y;‬
‭The public keyword is an access specifier. Access specifiers define how the‬
‭year = z;‬
‭members (attributes and methods) of a class can be accessed. In the example‬
‭}‬
‭above, the members are public - which means that they can be accessed and‬
‭int main() {‬
‭modified from outside the code.‬
‭// Create Car objects and call the constructor with different values‬

‭92‬ ‭93‬

‭However, what if we want members to be private and hidden from the outside‬
‭world?‬ ‭error: y is private‬
‭Note: It is possible to access private members of a class using a public method‬
‭In C++, there are three access specifiers:‬ ‭inside the same class. See the next chapter (Encapsulation) on how to do this.‬
‭public - members are accessible from outside the class‬
‭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‬
‭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‬
‭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‬
‭specifier:‬
‭Example‬
‭class MyClass {‬ ‭Example‬
‭public: // Public access specifier‬ ‭class MyClass {‬
‭int x; // Public attribute‬ ‭int x; // Private attribute‬
‭private: // Private access specifier‬ ‭int y; // Private attribute‬
‭int y; // Private attribute‬ ‭};‬
‭};‬
‭int main() {‬
‭MyClass myObj;‬ ‭C++ Encapsulation‬
‭myObj.x = 25; // Allowed (public)‬
‭Encapsulation‬
‭myObj.y = 50; // Not allowed (private)‬
‭The meaning of Encapsulation, is to make sure that "sensitive" data is hidden‬
‭return 0;‬
‭from users. To achieve this, you must declare class variables/attributes as private‬
‭}‬
‭(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.‬

‭94‬ ‭95‬
‭}‬
‭Access Private Members‬ ‭Example explained‬
‭To access a private attribute, use public "get" and "set" methods:‬ ‭The salary attribute is private, which have restricted access.‬
‭Example‬ ‭The public setSalary() method takes a parameter (s) and assigns it to the salary‬
‭#include <iostream>‬ ‭attribute (salary = s).‬
‭using namespace std;‬ ‭The public getSalary() method returns the value of the private salary attribute.‬
‭class Employee {‬ ‭Inside main(), we create an object of the Employee class. Now we can use the‬
‭private:‬ ‭setSalary() method to set the value of the private attribute to 50000. Then we call‬
‭// Private attribute‬ ‭the getSalary() method on the object to return the value.‬
‭int salary;‬
‭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‬
‭salary = s;‬ ‭others) can change one part of the code without affecting other parts‬
‭}‬ ‭Increased security of data‬
‭// Getter‬
‭int getSalary() {‬
‭return salary;‬ ‭C++ Inheritance‬
‭}‬
‭Inheritance‬
‭};‬
‭In C++, it is possible to inherit attributes and methods from one class to‬
‭int main() {‬
‭another. We group the "inheritance concept" into two categories:‬
‭Employee myObj;‬
‭myObj.setSalary(50000);‬
‭derived class (child) - the class that inherits from another class‬
‭cout << myObj.getSalary();‬
‭base class (parent) - the class being inherited from‬
‭return 0;‬
‭To inherit from a class, use the : symbol.‬

‭96‬ ‭97‬

‭- It is useful for code reusability: reuse attributes and methods of an existing‬


‭In the example below, the Car class (child) inherits the attributes and methods‬ ‭class when you create a new class.‬
‭from the Vehicle class (parent):‬
‭Example‬
‭// Base class‬ ‭C++ Multilevel Inheritance‬
‭class Vehicle {‬
‭Multilevel Inheritance‬
‭public:‬
‭A class can also be derived from one class, which is already derived from‬
‭string brand = "Ford";‬
‭another class.‬
‭void honk() {‬
‭cout << "Tuut, tuut! \n" ;‬
‭In the following example, MyGrandChild is derived from class MyChild (which‬
‭}‬
‭is derived from MyClass).‬
‭};‬
‭Example‬
‭// Derived class‬
‭// Base class (parent)‬
‭class Car: public Vehicle {‬
‭class MyClass {‬
‭public:‬
‭public:‬
‭string model = "Mustang";‬
‭void myFunction() {‬
‭};‬
‭cout << "Some content in parent class." ;‬
‭int main() {‬
‭}‬
‭Car myCar;‬
‭};‬
‭myCar.honk();‬
‭// Derived class (child)‬
‭cout << myCar.brand + " " + myCar.model;‬
‭class MyChild: public MyClass {‬
‭return 0;‬
‭};‬
‭}‬
‭// Derived class (grandchild)‬
‭Why And When To Use "Inheritance"?‬
‭class MyGrandChild: public MyChild {‬
‭};‬

‭98‬ ‭99‬
‭int main() {‬ ‭};‬
‭MyGrandChild myObj;‬ ‭// Derived class‬
‭myObj.myFunction();‬ ‭class MyChildClass: public MyClass, public MyOtherClass {‬
‭return 0;‬ ‭};‬
‭}‬ ‭int main() {‬
‭MyChildClass myObj;‬

‭C++ Multiple Inheritance‬


‭myObj.myFunction();‬
‭myObj.myOtherFunction();‬
‭return 0;‬
‭Multiple Inheritance‬
‭}‬
‭A class can also be derived from more than one base class, using a‬
‭comma-separated list:‬
‭Example‬
‭// Base class‬
‭C++ Inheritance Access‬
‭class MyClass {‬ ‭Access Specifiers‬
‭public:‬ ‭You learned from the Access Specifiers chapter that there are three specifiers‬
‭void myFunction() {‬ ‭available in C++. Until now, we have only used public (members of a class are‬
‭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:‬
‭// Another base class‬ ‭Example‬
‭class MyOtherClass {‬ ‭// Base class‬
‭public:‬ ‭class Employee {‬
‭void myOtherFunction() {‬ ‭protected: // Protected access specifier‬
‭cout << "Some content in another class." ;‬ ‭int salary;‬
‭}‬ ‭};‬

‭100‬ ‭101‬

‭// Derived class‬


‭class Programmer: public Employee {‬ ‭Like we specified in the previous chapter; Inheritance lets us inherit attributes‬
‭public:‬ ‭and methods from another class. Polymorphism uses those methods to perform‬
‭int bonus;‬ ‭different tasks. This allows us to perform a single action in different ways.‬
‭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 -‬
‭int getSalary() {‬ ‭And they also have their own implementation of an animal sound (the pig oinks,‬
‭return salary;‬ ‭and the cat meows, etc.):‬
‭}‬ ‭Example‬
‭};‬ ‭// Base class‬
‭int main() {‬ ‭class Animal {‬
‭Programmer myObj;‬ ‭public:‬
‭myObj.setSalary(50000);‬ ‭void animalSound() {‬
‭myObj.bonus = 15000;‬ ‭cout << "The animal makes a sound \n";‬
‭cout << "Salary: " << myObj.getSalary() << "\n";‬ ‭}‬
‭cout << "Bonus: " << myObj.bonus << "\n";‬ ‭};‬
‭return 0;‬ ‭// Derived class‬
‭}‬ ‭class Pig : public Animal {‬
‭public:‬

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

‭102‬ ‭103‬
‭class Dog : public Animal {‬ ‭class Dog : public Animal {‬
‭public:‬ ‭public:‬
‭void animalSound() {‬ ‭void animalSound() {‬
‭cout << "The dog says: bow wow \n";‬ ‭cout << "The dog says: bow wow \n";‬
‭}‬ ‭}‬
‭};‬ ‭};‬
‭Remember from the Inheritance chapter that we use the : symbol to inherit from‬ ‭int main() {‬
‭a class.‬ ‭Animal myAnimal;‬
‭Now we can create Pig and Dog objects and override the animalSound() method:‬ ‭Pig myPig;‬
‭Example‬ ‭Dog myDog;‬
‭// Base class‬ ‭myAnimal.animalSound();‬
‭class Animal {‬ ‭myPig.animalSound();‬
‭public:‬ ‭myDog.animalSound();‬
‭void animalSound() {‬ ‭return 0;‬
‭cout << "The animal makes a sound \n";‬ ‭}‬
‭}‬ ‭Why And When To Use "Inheritance" and "Polymorphism"?‬
‭};‬ ‭- It is useful for code reusability: reuse attributes and methods of an existing‬
‭// Derived class‬ ‭class when you create a new class.‬
‭class Pig : public Animal {‬
‭public:‬
‭void animalSound() {‬ ‭C++ Files‬
‭cout << "The pig says: wee wee \n";‬
‭C++ Files‬
‭}‬
‭The fstream library allows us to work with files.‬
‭};‬
‭To use the fstream library, include both the standard <iostream> AND the‬
‭// Derived class‬
‭<fstream> header file:‬

‭104‬ ‭105‬

‭Example‬ ‭MyFile.close();‬
‭#include <iostream>‬ ‭}‬
‭#include <fstream>‬ ‭Why do we close the file?‬
‭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‬
‭ofstream‬ ‭Creates and writes to files‬ ‭To read from a file, use either the ifstream or fstream class, and the name of the‬
‭ifstream‬ ‭Reads from files‬ ‭file.‬
‭fstream‬ ‭A combination of ofstream and ifstream: creates, reads, and‬
‭writes to files‬ ‭Note that we also use a while loop together with the getline() function (which‬
‭Create and Write To a File‬ ‭belongs to the ifstream class) to read the file line by line, and to print the‬
‭To create a file, use either the ofstream or fstream class, and specify the name of‬ ‭content of the file:‬
‭the file.‬ ‭Example‬
‭// Create a text string, which is used to output the text file‬
‭To write to the file, use the insertion operator (<<).‬ ‭string myText;‬
‭Example‬ ‭// Read from the text file‬
‭#include <iostream>‬ ‭ifstream MyReadFile("filename.txt");‬
‭#include <fstream>‬ ‭// Use a while loop together with the getline() function to read the file‬
‭using namespace std;‬ ‭line by line‬
‭int main() {‬ ‭while (getline (MyReadFile, myText)) {‬
‭// Create and open a text file‬ ‭// Output the text from the file‬
‭ofstream MyFile("filename.txt");‬ ‭cout << myText;‬
‭// Write to the file‬ ‭}‬
‭MyFile << "Files can be tricky, but it is fun enough!";‬ ‭// Close the file‬
‭// Close the file‬ ‭MyReadFile.close();‬

‭106‬ ‭107‬
‭// Block of code to handle errors‬

‭C++ Exceptions‬
‭}‬
‭Consider the following example:‬

‭C++ Exceptions‬
‭Example‬
‭When executing C++ code, different errors can occur: coding errors made by the‬
‭try {‬
‭programmer, errors due to wrong input, or other unforeseeable things.‬
‭int age = 15;‬
‭When an error occurs, C++ will normally stop and generate an error message.‬
‭if (age >= 18) {‬
‭The technical term for this is: C++ will throw an exception (throw an error).‬
‭cout << "Access granted - you are old enough.";‬
‭} else {‬
‭C++ try and catch‬
‭throw (age);‬
‭Exception handling in C++ consist of three keywords: try, throw and catch:‬
‭}‬
‭The try statement allows you to define a block of code to be tested for errors‬
‭}‬
‭while it is being executed.‬
‭catch (int myNum) {‬
‭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";‬
‭us create a custom error.‬
‭cout << "Age is: " << myNum;‬
‭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‬
‭throw an exception, and handle it in our catch block.‬
‭Example‬
‭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)‬
‭throw exception; // Throw an exception when a problem arise‬
‭(because we are throwing an exception of int type in the try block (age)), to‬
‭}‬
‭output the value of age.‬
‭catch () {‬

‭108‬ ‭109‬

‭If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater‬ ‭Example‬
‭than 18), the catch block is skipped:‬ ‭try {‬
‭int age = 15;‬
‭Example‬ ‭if (age >= 18) {‬
‭int age = 20;‬ ‭cout << "Access granted - you are old enough.";‬
‭You can also use the throw keyword to output a reference number, like a custom‬ ‭} else {‬
‭error number/code for organizing purposes:‬ ‭throw 505;‬
‭}‬
‭Example‬ ‭}‬
‭try {‬ ‭catch (...) {‬
‭int age = 15;‬ ‭cout << "Access denied - You must be at least 18 years old.\n";‬
‭if (age >= 18) {‬ ‭}‬
‭cout << "Access granted - you are old enough.";‬
‭} else {‬ ‭C++ How To Add Two Numbers‬
‭throw 505;‬
‭Add Two Numbers‬
‭}‬
‭Learn how to add two numbers in C++:‬
‭}‬
‭Example‬
‭catch (int myNum) {‬
‭int x = 5;‬
‭cout << "Access denied - You must be at least 18 years old.\n";‬
‭int y = 6;‬
‭cout << "Error number: " << myNum;‬
‭int sum = x + y;‬
‭}‬
‭cout << sum;‬
‭Handle Any Type of Exceptions (...)‬
‭Add Two Numbers with User Input‬
‭If you do not know the throw type used in the try block, you can use the "three‬
‭In this example, the user must input two numbers. Then we print the sum by‬
‭dots" syntax (...) inside the catch block, which will handle any type of exception:‬
‭calculating (adding) the two numbers:‬

‭110‬ ‭111‬
‭Example‬ ‭Const‬ ‭Defines a variable or parameter as a constant (unchangeable) or‬
‭int x, y;‬ ‭specifies that a class method does not modify attributes of the class‬
‭int sum;‬ ‭continue‬ ‭Continues to the next iteration of a loop‬
‭cout << "Type a number: ";‬ ‭default‬ ‭Specifies the default block of code in a switch statement‬
‭cin >> x;‬ ‭delete‬ ‭Frees dynamic memory‬
‭cout << "Type another number: ";‬ ‭do‬ ‭Used together with while to create a do/while loop‬
‭cin >> y;‬ ‭double‬ ‭A data type that is usually 64 bits long which can store fractional‬
‭sum = x + y;‬ ‭numbers‬
‭cout << "Sum is: " << sum;‬ ‭else‬ ‭Used in conditional statements‬

‭C++ Keywords‬
‭enum‬ ‭Declares an enumerated type‬
‭false‬ ‭A boolean value equivalent to 0‬
‭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.‬
‭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‬
‭and_eq‬ ‭An alternative way to write the &= assignment operator‬
‭goto‬ ‭Jumps to a line of code specified by a label‬
‭bitand‬ ‭An alternative way to write the & bitwise operator‬
‭if‬ ‭Makes a conditional statement‬
‭bitor‬ ‭An alternative way to write the | bitwise operator‬
‭int‬ ‭A data type that is usually 32 bits long which can store whole‬
‭bool‬ ‭A data type that can only store true or false values‬
‭numbers‬
‭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‬
‭case‬ ‭Marks a block of code in switch statements‬
‭ensure 64 bits)‬
‭catch‬ ‭Catches exceptions generated by try statements‬
‭namespace‬ ‭Declares a namespace‬
‭char‬ ‭A data type that can store a single character‬
‭new‬ ‭Reserves dynamic memory‬
‭class‬ ‭Defines a class‬
‭not‬ ‭An alternative way to write the logical ! operator‬
‭compl‬ ‭An alternative way to write the ~ bitwise operator‬

‭112‬ ‭113‬

‭not_eq‬ ‭An alternative way to write the != comparison operator‬ ‭true‬ ‭A boolean value equivalent to 1‬
‭or‬ ‭An alternative way to write the logical || operator‬ ‭try‬ ‭Creates a try...catch statement‬
‭or_eq‬ ‭An alternative way to write the |= assignment operator‬ ‭typedef‬ ‭Defines a custom data type‬
‭private‬ ‭An access modifier which makes a member only‬‭accessible‬ ‭unsigned‬ ‭Specifies that an int or char should only‬‭represent positive values‬
‭within the declared class‬ ‭which allows for storing numbers up to twice as large‬
‭protected‬ ‭An access modifier which makes a member‬‭only accessible‬ ‭using‬ ‭Allows variables and functions from a namespace‬‭to be used‬
‭within the declared class and its children‬ ‭without the namespace's prefix‬
‭public‬ ‭An access modifier which makes a member accessible from‬ ‭virtual‬ ‭Specifies that a class method is virtual‬
‭anywhere‬ ‭void‬ ‭Indicates a function that does not return a‬‭value or specifies a‬
‭return‬ ‭Used to return a value from a function‬ ‭pointer to a data with an unspecified type‬
‭short‬ ‭Reduces the size of an integer to 16 bits‬ ‭while‬ ‭Creates a while loop‬
‭signed‬ ‭Specifies that an int or char can represent‬‭positive and negative‬ ‭xor‬ ‭An alternative way to write the ^ bitwise operator‬
‭values (this is the default so the keyword is not usually necessary)‬ ‭xor_eq‬ ‭An alternative way to write the ^= assignment operator‬
‭sizeof‬ ‭An operator that returns the amount of memory occupied by a‬
‭variable or data type‬
‭static‬ ‭Specifies that an attribute or method belongs‬‭to the class itself‬ ‭C++ Math Functions‬
‭instead of instances of the classSpecifies that a variable in a function keeps its‬
‭C++ Math Functions‬
‭value after the function ends‬
‭The <cmath> library has many functions that allow you to perform mathematical‬
‭struct‬ ‭Defines a structure‬
‭tasks on numbers.‬
‭switch‬ ‭Selects one of many code blocks to be executed‬
‭template‬ ‭Declares a template class or template function‬
‭A list of all math functions can be found in the table below:‬
‭this‬ ‭A variable that is available inside class methods‬‭and constructors‬
‭which contians a pointer to a class instance‬
‭Function‬ ‭Description‬
‭throw‬ ‭Creates a custom error which can be caught‬‭by a try...catch‬
‭abs(x)‬ ‭Returns the absolute value of x‬
‭statement‬
‭acos(x)‬ ‭Returns the arccosine of x, in radians‬

‭114‬ ‭115‬
‭acosh(x)‬ ‭Returns the hyperbolic arccosine of x‬ ‭fmin(x, y)‬ ‭Returns the lowest value of a floating x and y‬
‭asin(x)‬ ‭Returns the arcsine of x, in radians‬ ‭fmod(x, y)‬ ‭Returns the floating point remainder of x/y‬
‭asinh(x)‬ ‭Returns the hyperbolic arcsine of x‬ ‭frexp(x, y)‬ ‭With x expressed as m*2n, returns the‬‭value of m (a value between‬
‭atan(x)‬ ‭Returns the arctangent of x as a numeric‬‭value between‬ ‭0.5 and 1.0) and writes the value of n to the memory at the pointer y‬
‭-PI/2 and PI/2 radians‬ ‭hypot(x, y)‬ ‭Returns sqrt(x2 +y2) without intermediate overflow or‬
‭atan2(y, x)‬ ‭Returns the angle theta from the conversion‬‭of‬ ‭underflow‬
‭rectangular coordinates (x, y) to polar coordinates (r, theta)‬ ‭ilogb(x)‬ ‭Returns the integer part of the floating-point‬‭base‬
‭atanh(x)‬ ‭Returns the hyperbolic arctangent of x‬ ‭logarithm of x‬
‭cbrt(x)‬ ‭Returns the cube root of x‬ ‭ldexp(x, y)‬ ‭Returns x*2y‬
‭ceil(x)‬ ‭Returns the value of x rounded up to its nearest integer‬ ‭lgamma(x)‬ ‭Returns the logarithm of the absolute value‬‭of the gamma‬
‭copysign(x, y)‬ ‭Returns the first floating point x‬‭with the sign of the‬ ‭function at x‬
‭second floating point y‬ ‭llrint(x)‬ ‭Rounds x to a nearby integer and returns‬‭the result as a‬
‭cos(x)‬ ‭Returns the cosine of x (x is in radians)‬ ‭long long integer‬
‭cosh(x)‬ ‭Returns the hyperbolic cosine of x‬ ‭llround(x)‬ ‭Rounds x to the nearest integer and returns the result as a‬
‭exp(x)‬ ‭Returns the value of Ex‬ ‭long long integer‬
‭exp2(x)‬ ‭Returns the value of 2x‬ ‭log(x)‬ ‭Returns the natural logarithm of x‬
‭expm1(x)‬ ‭Returns ex-1‬ ‭log10(x)‬ ‭Returns the base 10 logarithm of x‬
‭erf(x)‬ ‭Returns the value of the error function at x‬ ‭log1p(x)‬ ‭Returns the natural logarithm of x+1‬
‭erfc(x)‬ ‭Returns the value of the complementary error function at‬ ‭log2(x)‬ ‭Returns the base 2 logarithm of the absolute value of x‬
‭x‬ ‭logb(x)‬ ‭Returns the floating-point base logarithm‬‭of the absolute‬
‭fabs(x)‬ ‭Returns the absolute value of a floating x‬ ‭value of x‬
‭fdim(x)‬ ‭Returns the positive difference between x and y‬ ‭lrint(x)‬ ‭Rounds x to a nearby integer and returns‬‭the result as a‬
‭floor(x)‬ ‭Returns the value of x rounded down to its nearest integer‬ ‭long integer‬
‭fma(x, y, z)‬ ‭Returns x*y+z without losing precision‬ ‭lround(x)‬ ‭Rounds x to the nearest integer and returns‬‭the result as a‬
‭fmax(x, y)‬ ‭Returns the highest value of a floating x and y‬ ‭long integer‬

‭116‬ ‭117‬

‭modf(x, y)‬ ‭Returns the decimal part of x and writes the integer part‬
‭to the memory at the pointer y‬
‭nan(s)‬ ‭Returns a NaN (Not a Number) value‬
‭nearbyint(x)‬ ‭Returns x rounded to a nearby integer‬
‭nextafter(x, y)‬ ‭Returns the closest floating point‬‭number to x in the‬
‭direction of y‬
‭nexttoward(x, y)‬ ‭Returns the closest floating point‬‭number to x in the‬
‭direction of y‬
‭pow(x, y)‬ ‭Returns the value of x to the power of y‬
‭remainder(x, y)‬ ‭Return the remainder of x/y rounded to the nearest‬
‭integer‬
‭remquo(x, y, z)‬ ‭Calculates x/y rounded to the nearest‬‭integer, writes the‬
‭result to the memory at the pointer z and returns the remainder.‬
‭rint(x)‬ ‭Returns x rounded to a nearby integer‬
‭round(x)‬ ‭Returns x rounded to the nearest integer‬
‭scalbln(x, y)‬ ‭Returns x*Ry (R is usually 2)‬
‭scalbn(x, y)‬ ‭Returns x*Ry (R is usually 2)‬
‭sin(x)‬ ‭Returns the sine of x (x is in radians)‬
‭sinh(x)‬ ‭Returns the hyperbolic sine of x‬
‭sqrt(x)‬ ‭Returns the square root of x‬
‭tan(x)‬ ‭Returns the tangent of x (x is in radians)‬
‭tanh(x)‬ ‭Returns the hyperbolic tangent of x‬
‭tgamma(x)‬ ‭Returns the value of the gamma function at x‬
‭trunc(x)‬ ‭Returns the integer part of x‬

‭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