C++ Menu: C++ Output (Print Text)
C++ Menu: C++ Output (Print Text)
C++ Menu
C++ Recursion 79-81
C++ Classes
C++ OOP 81-83
Title pagenumber
C++ Classes/Objects 83-87
C++ Syntax 2-3 C++ Class Methods 87-89
C++ Output 4-7 C++ Constructors 89-93
C++ Comments 7-8 C++ Access Specifiers 93-95
C++
C++ Variables 8-13 C++ Encapsulation 95-97
C++ User Input 13-14 C++ Inheritance 97-102
C++ Data Types 14-18 C++ Polymorphism 102-105
C++ Operators 18-22 C++ Files 105-107
C++ Strings 23-30 C++ Exceptions 108-111
C++ Math 30-32 Add Two Numbers 111-112
C++ Booleans 32-34 C++ Reference
C++ Conditions(if……else) 35-39 C++ Keywords 112-115
C++ Switch 39-42 C++ Math Functions 115-118
A complete guide to C++ While Loop 42-44
C++ For Loop 44-46 C++ Syntax
c++
C++ Break/Continue 46-48
C++ Arrays 48-59 C++ Syntax
et's break up the following code to understand it better:
L
C++ Structures 59-63 Example
C++ References 63-64 #include <iostream>
C++ Pointers 64-67 using namespace std;
C++ Functions 67-71 int main() {
C++ Function Parameters 71-77 cout << "Hello World!";
1 2
return 0; Line 7: Do not forget to add the closing curly bracket } to actually end the main You can add as many cout objects as you want. However, note that it does not
} function. insert a new line at the end of the output:
Example explained Omitting Namespace Example
Line 1: #include <iostream> is a header file library that lets us work with input You might see some C++ programs that runs without the standard namespace #include <iostream>
and output objects, such as cout (used in line 5). Header files add functionality to library. The using namespace std line can be omitted and replaced with the std using namespace std;
C++ programs. keyword, followed by the :: operator for some objects: int main() {
Line 2: using namespace std means that we can use names for objects and Example cout << "Hello World!";
variables from the standard library. #include <iostream> cout << "I am learning C++";
It is up to you if you want to include the standard namespace library or not. To insert a new line, you can use the \n character:
Line 3: A blank line. C++ ignores white space. But we use it to make the code Example
more readable. C++ Output (Print Text) #include <iostream>
Line 4: Another thing that always appear in a C++ program is int main(). This is using namespace std;
C++ Output (Print Text)
called a function. Any code inside its curly brackets {} will be executed. int main() {
The cout object, together with the << operator, is used to output values/print
Line 5: cout (pronounced "see-out") is an object used together with the insertion cout << "Hello World! \n";
text:
operator (<<) to output/print text. In our example, it will output "Hello World!". cout << "I am learning C++";
Example
Note: Every C++ statement ends with a semicolon ;. return 0;
#include <iostream>
Note: The body of int main() could also been written as: }
using namespace std;
int main () { cout << "Hello world! "; return 0; } Tip : Two \n characters after each other will create a blank line:
int main() {
Remember: The compiler ignores white spaces. However, multiple lines makes
cout << "Hello World!";
the code more readable. Example
return 0; }
Line 6: return 0 ends the main function. #include <iostream>
using namespace std; \t Creates a horizontal tab /* The code below will print the words Hello World!
int main() { \\ Inserts a backslash character (\) to the screen, and it is amazing */
cout << "Hello World! \n\n"; \" Inserts a double quote character cout << "Hello World!";
cout << "I am learning C++"; Single or multi-line comments?
return 0; C++ Comments It is up to you which you want to use. Normally, we use // for short comments,
} and /* */ for longer.
C++ Comments
Another way to insert a new line, is with the endl manipulator:
Example
Comments can be used to explain C++ code, and to make it more readable. It can C++ Variables
also be used to prevent execution when testing alternative code. Comments can
#include <iostream>
be single-lined or multi-lined. C++ Variables
using namespace std;
Variables are containers for storing data values.
int main() {
Single-line Comments In C++, there are different types of variables (defined with different keywords),
cout << "Hello World!" << endl;
Single-line comments start with two forward slashes (//). for example:
cout << "I am learning C++";
Any text between // and the end of the line is ignored by the compiler (will not int - stores integers (whole numbers), without decimals, such as 123 or -123
return 0;
be executed). double - stores floating point numbers, with decimals, such as 19.99 or -19.99
}
This example uses a single-line comment before a line of code: char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
Both \n and endl are used to break lines. However, \n is most used.
Example single quotes
// This is a comment string - stores text, such as "Hello World". String values are surrounded by
But what is \n exactly?
cout << "Hello World!"; double quotes
The newline character (\n) is called an escape sequence, and it forces the cursor
This example uses a single-line comment at the end of a line of code: bool - stores values with two states: true or false
to change its position to the beginning of the next line on the screen. This
Example
results in a new line.
cout << "Hello World!"; // This is a comment Declaring (Creating) Variables
C++ Multi-line Comments To create a variable, specify the type and assign it a value:
Examples of other valid escape sequences are:
Multi-line comments start with /* and ends with */. Syntax
Any text between /* and */ will be ignored by the compiler: type variableName = value;
Escape Sequence description
Example
6 7 8
Where type is one of C++ types (such as int), and variableName is the name of int myNum = 5; // Integer (whole number without decimals) Example
the variable (such as x or myName). The equal sign is used to assign values to the double myFloatNum = 5.99; // Floating point number (with decimals) int x = 5, y = 6, z = 50;
variable. char myLetter = 'D'; // Character cout << x + y + z;
To create a variable that should store a number, look at the following example: string myText = "Hello"; // String (text) One Value to Multiple Variables
Example bool myBoolean = true; // Boolean (true or false) You can also assign the same value to multiple variables in one line:
Create a variable called myNum of type int and assign it the value 15: You will learn more about the individual types in the Data Types chapter. Example
int myNum = 15; int x, y, z;
cout << myNum; Display Variables x = y = z = 50;
You can also declare a variable without assigning the value, and assign the value The cout object is used together with the << operator to display variables. cout << x + y + z;
later: To combine both text and a variable, separate them with the << operator:
Example C++ Identifiers
int myNum; Example C++ Identifiers
myNum = 15; int myAge = 35; All C++ variables must be identified with unique names.
cout << myNum; cout << "I am " << myAge << " years old."; These unique names are called identifiers.
Note that if you assign a new value to an existing variable, it will overwrite the Add Variables Together Identifiers can be short names (like x and y) or more descriptive names (age,
previous value: To add a variable to another variable, you can use the + operator: sum, totalVolume).
Example
Example int x = 5; Note: It is recommended to use descriptive names in order to create
int myNum = 15; // myNum is 15 int y = 6; understandable and maintainable code:
myNum = 10; // Now myNum is 10 int sum = x + y; Example
cout << myNum; // Outputs 10 cout << sum; // Good
Other Types int minutesPerHour = 60;
A demonstration of other data types: C++ Declare Multiple Variables // OK, but not so easy to understand what m actually is
Declare Many Variables int m = 60;
Example To declare more than one variable of the same type, use a comma-separated list: The general rules for naming variables are:
This however, will not work: In this example, the user must input two numbers. Then we print the sum by
Names can contain letters, digits and underscores const int minutesPerHour; calculating (adding) the two numbers:
Names must begin with a letter or an underscore (_) minutesPerHour = 60; // error
Names are case-sensitive (myVar and myvar are different variables)
C++ User Input
Example
Names cannot contain whitespaces or special characters like !, #, %, etc. int x, y;
Reserved words (like C++ keywords, such as int) cannot be used as names int sum;
C++ User Input
C++ Constants
cout << "Type a number: ";
You have already learned that cout is used to output (print) values. Now we will
cin >> x;
use cin to get user input.
cout << "Type another number: ";
Constants cin is a predefined variable that reads data from the keyboard with the
cin >> y;
When you do not want others (or yourself) to change existing variable values, use extraction operator (>>).
sum = x + y;
the const keyword (this will declare the variable as "constant", which means In the following example, the user can input a number, which is stored in the
cout << "Sum is: " << sum;
unchangeable and read-only): variable x. Then we print the value of x:
Example
const int myNum = 15; // myNum will always be 15
Example
int x;
C++ Data Types
myNum = 10; // error: assignment of read-only variable 'myNum' cout << "Type a number: "; // Type a number and press enter C++ Data Types
You should always declare the variable as constant when you have values that cin >> x; // Get user input from the keyboard As explained in the Variables chapter, a variable in C++ must be a specified data
are unlikely to change: cout << "Your number is: " << x; // Display the input value type:
Example Good To Know Example
const int minutesPerHour = 60; int myNum = 5; // Integer (whole number)
const float PI = 3.14; cout is pronounced "see-out". Used for output, and uses the insertion operator float myFloatNum = 5.99; // Floating point number
Notes On Constants (<<) double myDoubleNum = 9.98; // Floating point number
When you declare a constant variable, it must be assigned with a value: cin is pronounced "see-in". Used for input, and uses the extraction operator (>>) char myLetter = 'D'; // Character
Example bool myBoolean = true; // Boolean
Like this: Creating a Simple Calculator string myText = "Hello"; // String
const int minutesPerHour = 60; Basic Data Types
The data type specifies the size and type of information the variable will store: double myNum = 19.99; Example
cout << myNum; bool isCodingFun = true;
Data Type Size Description float vs. double bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
boolean 1 byte Stores true or false values
The precision of a floating point value indicates how many digits the value can cout << isFishTasty; // Outputs 0 (false)
char 1 byte Stores a single character/letter/number, or
have after the decimal point. The precision of float is only six or seven decimal Boolean values are mostly used for conditional testing
ASCII values
digits, while double variables have a precision of about 15 digits. Therefore it is
int 2 or 4 bytes Stores whole numbers, without decimals
safer to use double for most calculations. C++ Character Data Types
float 4 bytes Stores fractional numbers, containing one or more
decimals. Sufficient for storing 6-7 decimal digits Character Types
Scientific Numbers The char data type is used to store a single character. The character must be
double 8 bytes Stores fractional numbers, containing one or more
A floating point number can also be a scientific number with an "e" to indicate surrounded by single quotes, like 'A' or 'c':
decimals. Sufficient for storing 15 decimal digits
the power of 10: Example
C++ Numeric Data Types char myGrade = 'B';
Example cout << myGrade;
Numeric Types
float f1 = 35e3; Alternatively, if you are familiar with ASCII, you can use ASCII values to display
Use int when you need to store a whole number without decimals, like 35 or
double d1 = 12E4; certain characters:
1000, and float or double when you need a floating point number (with
cout << f1; Example
decimals), like 9.99 or 3.14515.
cout << d1; char a = 65, b = 66, c = 67;
C++ Operators
Operator Name Description
Example
Example
int x = 10;
C++ Operators + Addition Adds together two values
x += 5;
Operators are used to perform operations on variables and values. x + y
A list of all assignment operators:
In the example below, we use the + operator to add together two values: - Subtraction Subtracts one value from another
Example x - y
Operator Example Same As
int x = 100 + 50; * Multiplication Multiplies two values
= x = 5 x = 5
x * y
+= x += 3 x = x + 3
Logical Operators
Example
Comparison Operators As with comparison operators, you can also test for true (1) or false (0) values
// Include the string library
Comparison operators are used to compare two values (or variables). This is with logical operators.
#include <string>
important in programming, because it helps us to find answers and make Logical operators are used to determine the logic between variables or values:
// Create a string variable
decisions.
string greeting = "Hello";
The return value of a comparison is either 1 or 0, which means true (1) or false Operator Name Description
(0). These values are known as Boolean values, and you will learn more about
them in the Booleans and If..Else chapter. &&
Example
Logical and Returns true if both statements are true
C++ String Concatenation
In the following example, we use the greater than operator (>) to find out if 5 is x < 5 && x < 10 String Concatenation
greater than 3: || Logical or Returns true if one of the statements is true The + operator can be used between strings to add them together to make a new
Example x < 5 || x < 4 string. This is called concatenation:
int x = 5; ! Logical not Reverse the result, returns false if the result is true Example
int y = 3; !(x < 5 string firstName = "John ";
cout << (x > y); // returns 1 (true) because 5 is greater than 3
C++ Strings
string lastName = "Doe";
A list of all comparison operators: string fullName = firstName + lastName;
cout << fullName; Numbers are added. Strings are concatenated. Tip: You might see some C++ programs that use the size() function to get the
In the example above, we added a space after firstName to create a space If you add two numbers, the result will be a number: length of a string. This is just an alias of length(). It is completely up to you if
between John and Doe on output. However, you could also add a space with Example you want to use length() or size():
quotes (" " or ' '): int x = 10; Example
Example int y = 20; string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string firstName = "John"; int z = x + y; // z will be 30 (an integer) cout << "The length of the txt string is: " << txt.size();
string lastName = "Doe"; If you add two strings, the result will be a string concatenation:
string fullName = firstName + " " + lastName; Example C++ Access Strings
cout << fullName; string x = "10";
Access Strings
Append string y = "20";
You can access the characters in a string by referring to its index number inside
A string in C++ is actually an object, which contain functions that can perform string z = x + y; // z will be 1020 (a string)
square brackets [ ].
certain operations on strings. For example, you can also concatenate strings If you try to add a number to a string, an error occurs:
This example prints the first character in myString:
with the append() function: Example
Example
Example string x = "10";
string myString = "Hello";
string firstName = "John "; int y = 20;
cout << myString[0];
string lastName = "Doe"; string z = x + y;
// Outputs H
string fullName = firstName.append(lastName);
cout << fullName; C++ String Length Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
#include <iostream> #include <cmath> fmin(x, y) Returns the lowest value of a floating x and y
#include <string> cout << sqrt(64); fmod(x, y) Returns the floating point remainder of x/y
int main() { cout << round(2.6); pow(x, y) Returns the value of x to the power of y
std::string greeting = "Hello"; cout << log(2); sin(x) Returns the sine of x (x is in radians)
std::cout << greeting; Other Math Functions sinh(x) Returns the hyperbolic sine of a double value
return 0; A list of other popular Math functions (from the <cmath> library) can be found tan(x) Returns the tangent of an angle
} in the table below: tanh(x) Returns the hyperbolic tangent of a double value
It is up to you if you want to include the standard namespace library or not.
C++ Booleans
C++ Math
Function Description
abs(x) Returns the absolute value of x
C++ Booleans
acos(x) Returns the arccosine of x
C++ Math Very often, in programming, you will need a data type that can only have one of
asin(x) Returns the arcsine of x
C++ has many functions that allows you to perform mathematical tasks on two values, like:
atan(x) Returns the arctangent of x
numbers. YES / NO
cbrt(x) Returns the cube root of x
Max and min ON / OFF
ceil(x) Returns the value of x rounded up to its nearest integer
The max(x,y) function can be used to find the highest value of x and y: TRUE / FALSE
cos(x) Returns the cosine of x
Example For this, C++ has a bool data type, which can take the values true (1) or false (0).
cosh(x) Returns the hyperbolic cosine of x
cout << max(5, 10); Boolean Values
exp(x) Returns the value of Ex
And the min(x,y) function can be used to find the lowest value of x and y: A boolean variable is declared with the bool keyword and can only take the
expm1(x) Returns ex -1
Example values true or false:
fabs(x) Returns the absolute value of a floating x
cout << min(5, 10); Example
fdim(x, y) Returns the positive difference between x and y
C++ <cmath> Header bool isCodingFun = true;
floor(x) Returns the value of x rounded down to its nearest integer
Other functions, such as sqrt (square root), round (rounds a number) and log bool isFishTasty = false;
hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
(natural logarithm), can be found in the <cmath> header file: cout << isCodingFun; // Outputs 1 (true)
fma(x, y, z) Returns x*y+z without losing precision
Example cout << isFishTasty; // Outputs 0 (false)
fmax(x, y) Returns the highest value of a floating x and y
// Include the cmath library
From the example above, you can read that a true value returns 1, and false Real Life Example
returns 0. Let's think of a "real life example" where we need to find out if a person is old C++ If ... Else
However, it is more common to return a boolean value by comparing values and enough to vote.
C++ Conditions and If Statements
variables . In the example below, we use the >= comparison operator to find out if the age
You already know that C++ supports the usual logical conditions from
There is also a short-hand if else, which is known as the ternary operator // code block cout << "Wednesday";
because it consists of three operands. It can be used to replace multiple lines of break; break;
code with a single line. It is often used to replace simple if else statements: case y: case 4:
Syntax // code block cout << "Thursday";
variable = (condition) ? expressionTrue : expressionFalse; break; break;
Instead of writing: default: case 5:
Example // code block cout << "Friday";
int time = 20; } break;
if (time < 18) { This is how it works: case 6:
cout << "Good day."; The switch expression is evaluated once cout << "Saturday";
} else { The value of the expression is compared with the values of each case break;
cout << "Good evening."; If there is a match, the associated block of code is executed case 7:
} The break and default keywords are optional, and will be described later in this cout << "Sunday";
You can simply write: chapter break;
Example The example below uses the weekday number to calculate the weekday name: }
int time = 20; Example // Outputs "Thursday" (day 4)
string result = (time < 18) ? "Good day." : "Good evening."; int day = 4; The break Keyword
cout << result; switch (day) { When C++ reaches a break keyword, it breaks out of the switch block.
C++ Switch
case 1: This will stop the execution of more code and case testing inside the block.
cout << "Monday"; When a match is found, and the job is done, it's time for a break. There is no
break; need for more testing.
C++ Switch Statements
case 2: A break can save a lot of execution time because it "ignores" the execution of all
Use the switch statement to select one of many code blocks to be executed.
cout << "Tuesday"; the rest of the code in the switch block.
Syntax
break;
switch(expression) {
case 3: The default Keyword
case x:
The default keyword specifies some code to run if there is no case match: // code block to be executed The example below uses a do/while loop. The loop will always be executed at
Example } least once, even if the condition is false, because the code block is executed
int day = 4; In the example below, the code in the loop will run, over and over again, as long before the condition is tested:
switch (day) { as a variable (i) is less than 5: Example
case 6: Example int i = 0;
cout << "Today is Saturday"; int i = 0; do {
break; while (i < 5) { cout << i << "\n";
case 7: cout << i << "\n"; i++;
cout << "Today is Sunday"; i++; }
break; } while (i < 5);
default: Note: Do not forget to increase the variable used in the condition, otherwise the Do not forget to increase the variable used in the condition, otherwise the loop
cout << "Looking forward to the Weekend"; loop will never end! will never end!
}
// Outputs "Looking forward to the Weekend" C++ Do/While Loop C++ For Loop
C++ While Loop The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code
C++ For Loop
When you know exactly how many times you want to loop through a block of
C++ Loops block once, before checking if the condition is true, then it will repeat the loop code, use the for loop instead of a while loop:
Loops can execute a block of code as long as a specified condition is reached. as long as the condition is true. Syntax
Loops are handy because they save time, reduce errors, and they make code Syntax for (statement 1; statement 2; statement 3) {
more readable. do { // code block to be executed
C++ While Loop // code block to be executed }
The while loop loops through a block of code as long as a specified condition is } Statement 1 is executed (one time) before the execution of the code block.
true: while (condition); Statement 2 defines the condition for executing the code block.
Syntax Statement 3 is executed (every time) after the code block has been executed.
while (condition) {
int i = 0; string cars[4]; // Now outputs Opel instead of Volvo
while (i < 10) { We have now declared a variable that holds an array of four strings. To insert
cout << i << "\n"; values to it, we can use an array literal - place the values in a comma-separated C++ Arrays and Loops
i++; list, inside curly braces:
Loop Through an Array
if (i == 4) { string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
You can loop through the array elements with the for loop.
break; To create an array of three integers, you could write:
The following example outputs all elements in the cars array:
} int myNum[3] = {10, 20, 30};
Example
} Access the Elements of an Array
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
Continue Example You access an array element by referring to the index number inside square
for (int i = 0; i < 5; i++) {
int i = 0; brackets [].
cout << cars[i] << "\n";
while (i < 10) { This statement accesses the value of the first element in cars:
}
if (i == 4) { Example
This example outputs the index of each element together with its value:
i++; string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
Example
continue; cout << cars[0];
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
} // Outputs Volvo
for (int i = 0; i < 5; i++) {
cout << i << "\n"; Note: Array indexes start with 0: [0] is the first element. [1] is the second
cout << i << " = " << cars[i] << "\n";
i++; element, etc.
}
}
And this example shows how to loop through an array of integers:
C++ Arrays
Change an Array Element
Example
To change the value of a specific element, refer to the index number:
int myNumbers[5] = {10, 20, 30, 40, 50};
cars[0] = "Opel";
C++ Arrays for (int i = 0; i < 5; i++) {
Example
Arrays are used to store multiple values in a single variable, instead of declaring cout << myNumbers[i] << "\n";
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
separate variables for each value. }
cars[0] = "Opel";
To declare an array, define the variable type, specify the name of the array The foreach Loop
cout << cars[0];
followed by square brackets and specify the number of elements it should store:
There is also a "for-each loop" (introduced in C++ version 11 (2011), which is It is also possible to declare an array without specifying the elements on Loop Through an Array with sizeof()
used exclusively to loop through elements in an array: declaration, and add them later: In the Arrays and Loops Chapter, we wrote the size of the array in the loop
Syntax Example condition (i < 5). This is not ideal, since it will only work for arrays of a specified
for (type variableName : arrayName) { string cars[5]; size.
// code block to be executed cars[0] = "Volvo"; However, by using the sizeof() approach from the example above, we can now
} cars[1] = "BMW"; make loops that work for arrays of any size, which is more sustainable.
The following example outputs all elements in an array, using a "for-each loop":
C++ Array Size
Instead of writing:
Example int myNumbers[5] = {10, 20, 30, 40, 50};
int myNumbers[5] = {10, 20, 30, 40, 50}; for (int i = 0; i < 5; i++) {
Get the Size of an Array
for (int i : myNumbers) { cout << myNumbers[i] << "\n";
To get the size of an array, you can use the sizeof() operator:
cout << i << "\n"; }
Example
} It is better to write:
int myNumbers[5] = {10, 20, 30, 40, 50};
{ // Keep track of how many hits the player has and how many turns they }
{ "E", "F" }, have played in these variables // Count how many turns the player has taken
{ "G", "H" } int hits = 0; numberOfTurns++;
} int numberOfTurns = 0; }
}; // Allow the player to keep going until they have hit all four ships cout << "Victory!\n";
for (int i = 0; i < 2; i++) { while (hits < 4) { cout << "You won in " << numberOfTurns << " turns";
for (int j = 0; j < 2; j++) { int row, column;
for (int k = 0; k < 2; k++) { cout << "Selecting coordinates\n"; C++ Structures (struct)
cout << letters[i][j][k] << "\n"; // Ask the player for a row
C++ Structures
} cout << "Choose a row number between 0 and 3: ";
Structures (also called structs) are a way to group several related variables into
} cin >> row;
one place. Each variable in the structure is known as a member of the structure.
} // Ask the player for a column
Unlike an array, a structure can contain many different data types (int, string,
Why Multi-Dimensional Arrays? cout << "Choose a column number between 0 and 3: ";
bool, etc.).
Multi-dimensional arrays are great at representing grids. This example shows a cin >> column;
Create a Structure
practical use for them. In the following example we use a multi-dimensional // Check if a ship exists in those coordinates
To create a structure, use the struct keyword and declare each of its members
array to represent a small game of Battleship: if (ships[row][column]) {
inside curly braces.
Example // If the player hit a ship, remove it by setting the value to zero.
After the declaration, specify the name of the structure variable (myStructure in
// We put "1" to indicate there is a ship. ships[row][column] = 0;
the example below):
bool ships[4][4] = { // Increase the hit counter
struct { // Structure declaration
{ 0, 1, 1, 0 }, hits++;
int myNum; // Member (int variable)
{ 0, 0, 0, 0 }, // Tell the player that they have hit a ship and how many ships are left
string myString; // Member (string variable)
{ 0, 0, 1, 0 }, cout << "Hit! " << (4-hits) << " left.\n\n";
} myStructure; // Structure variable
{ 0, 0, 1, 0 } } else {
Access Structure Members
}; // Tell the player that they missed
To access members of a structure, use the dot syntax (.):
cout << "Miss\n\n";
Example
Assign data to members of a structure and print it: string model; string myString;
// Create a structure variable called myStructure int year; };
struct { } myCar1, myCar2; // We can add variables by separating them with a To declare a variable that uses the structure, use the name of the structure as the
int myNum; comma here data type of the variable:
string myString; // Put data into the first structure myDataType myVar;
} myStructure; myCar1.brand = "BMW"; Example
// Assign values to members of myStructure myCar1.model = "X5"; Use one structure to represent two cars:
myStructure.myNum = 1; myCar1.year = 1999; // Declare a structure named "car"
myStructure.myString = "Hello World!"; // Put data into the second structure struct car {
// Print members of myStructure myCar2.brand = "Ford"; string brand;
cout << myStructure.myNum << "\n"; myCar2.model = "Mustang"; string model;
cout << myStructure.myString << "\n"; myCar2.year = 1969; int year;
One Structure in Multiple Variables // Print the structure members };
You can use a comma (,) to use one structure in many variables: cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << int main() {
struct { "\n"; // Create a car structure and store it in myCar1;
int myNum; cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << car myCar1;
string myString; "\n"; myCar1.brand = "BMW";
} myStruct1, myStruct2, myStruct3; // Multiple structure variables Named Structures myCar1.model = "X5";
separated with By giving a name to the structure, you can treat it as a data type. This means myCar1.year = 1999;
commas that you can create variables with this structure anywhere in the program at any
This example shows how to use a structure in two different variables: time. // Create another car structure and store it in myCar2;
Example To create a named structure, put the name of the structure right after the struct car myCar2;
Use one structure to represent two cars: keyword: myCar2.brand = "Ford";
struct { struct myDataType { // This structure is named "myDataType" myCar2.model = "Mustang";
string brand; int myNum; myCar2.year = 1969;
C++ References
is stored: Example
Example string food = "Pizza"; // A food variable of type string
string food = "Pizza"; string* ptr = &food; // A pointer variable, with the name ptr, that stores
Creating References
cout << &food; // Outputs 0x6dfed4 the address of food
A reference variable is a "reference" to an existing variable, and it is created
Note: The memory address is in hexadecimal form (0x..). Note that you may not // Output the value of food (Pizza)
with the & operator:
get the same result in your program. cout << food << "\n";
string food = "Pizza"; // food variable
And why is it useful to know the memory address? // Output the memory address of food (0x6dfed4)
string &meal = food; // reference to food
References and Pointers (which you will learn about in the next chapter) are cout << &food << "\n";
Now, we can use either the variable name food or the reference name meal to
important in C++, because they give you the ability to manipulate the data in the // Output the memory address of food with the pointer (0x6dfed4)
refer to the food variable:
computer's memory - which can reduce the code and improve the performance. cout << ptr << "\n";
Example
These two features are one of the things that make C++ stand out from other Example explained
string food = "Pizza";
programming languages, like Python and Java. Create a pointer variable with the name ptr, that points to a string variable, by
string &meal = food;
C++ Pointers
using the asterisk sign * (string* ptr). Note that the type of the pointer has to
cout << food << "\n"; // Outputs Pizza
match the type of the variable you're working with.
cout << meal << "\n"; // Outputs Pizza
Use the & operator to store the memory address of the variable called food, and
Creating Pointers
assign it to the pointer.
You learned from the previous chapter, that we can get the memory address of a
Now, ptr holds the value of food's memory address.
Tip: There are three ways to declare pointer variables, but the first way is
C++ Modify Pointers
Functions are used to perform certain actions, and they are important for
preferred: reusing code: Define the code once, and use it many times.
Create a Function
Modify the Pointer Value
string* mystring; // Preferred C++ provides some pre-defined functions, such as main(), which is used to
You can also change the pointer's value. But note that this will also change the
string *mystring; execute code. But you can also create your own functions to perform certain
value of the original variable:
string * mystring; actions.
Example
C++ Dereference
To create (often referred to as declare) a function, specify the name of the
string food = "Pizza";
function, followed by parentheses ():
string* ptr = &food;
Syntax
Get Memory Address and Value // Output the value of food (Pizza)
void myFunction() {
In the example from the previous page, we used the pointer variable to get the cout << food << "\n";
// code to be executed
memory address of a variable (used together with the & reference operator). // Output the memory address of food (0x6dfed4)
}
However, you can also use the pointer to get the value of the variable, by using cout << &food << "\n";
Example Explained
the * operator (the dereference operator): // Access the memory address of food and output its value (Pizza)
myFunction() is the name of the function
Example cout << *ptr << "\n";
void means that the function does not have a return value. You will learn more
string food = "Pizza"; // Variable declaration // Change the value of the pointer
about return values later in the next chapter
string* ptr = &food; // Pointer declaration *ptr = "Hamburger";
inside the function (the body), add code that defines what the function should do
// Reference: Output the memory address of food with the pointer // Output the new value of the pointer (Hamburger)
Call a Function
(0x6dfed4) cout << *ptr << "\n";
Declared functions are not executed immediately. They are "saved for later use",
cout << ptr << "\n"; // Output the new value of the food variable (Hamburger)
and will be executed later, when they are called.
// Dereference: Output the value of food with the pointer (Pizza) cout << food << "\n";
To call a function, write the function's name followed by two parentheses () and
cout << *ptr << "\n";
Note that the * sign can be confusing here, as it does two different things in our C++ Functions a semicolon ;
In the following example, myFunction() is used to print a text (the action), when
code:
A function is a block of code which only runs when it is called. it is called:
When used in declaration (string* ptr), it creates a pointer variable.
You can pass data, known as parameters, into a function. Example
When not used in declaration, it act as a dereference operator.
C++ Recursion
return 0;
cout << "Int: " << myNum1 << "\n";
}
cout << "Double: " << myNum2;
Example Explained
return 0; Recursion
}
C++ OOP
C++ What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Everything in C++ is associated with classes and objects, along with its Inside the class, there is an integer variable myNum and a string variable myObj.myString = "Some text";
attributes and methods. For example: in real life, a car is an object. The car has myString. When variables are declared within a class, they are called attributes. // Print attribute values
attributes, such as weight and color, and methods, such as drive and brake. At last, end the class definition with a semicolon ;. cout << myObj.myNum << "\n";
Create an Object cout << myObj.myString;
Attributes and methods are basically variables and functions that belongs to the In C++, an object is created from a class. We have already created the class return 0;
class. These are often referred to as "class members". named MyClass, so now we can use this to create objects. }
Multiple Objects
A class is a user-defined data type that we can use in our program, and it works To create an object of MyClass, specify the class name, followed by the object You can create multiple objects of one class:
as an object constructor, or a "blueprint" for creating objects. name.
Example
Create a Class To access the class attributes (myNum and myString), use the dot syntax (.) on // Create a Car class with some attributes
To create a class, use the class keyword: the object: class Car {
Example public:
Create a class called "MyClass": Example string brand;
Create an object called "myObj" and access the attributes: string model;
class MyClass { // The class int year;
public: // Access specifier class MyClass { // The class };
int myNum; // Attribute (int variable) public: // Access specifier int main() {
string myString; // Attribute (string variable) int myNum; // Attribute (int variable) // Create an object of Car
}; string myString; // Attribute (string variable) Car carObj1;
Example explained }; carObj1.brand = "BMW";
The class keyword is used to create a class called MyClass. int main() { carObj1.model = "X5";
The public keyword is an access specifier, which specifies that members MyClass myObj; // Create an object of MyClass carObj1.year = 1999;
(attributes and methods) of the class are accessible from outside the class. You // Access attributes and set values // Create another object of Car
will learn more about access specifiers later. myObj.myNum = 15; Car carObj2;
carObj2.brand = "Ford"; void myMethod() { // Method/function defined inside the class myObj.myMethod(); // Call the method
carObj2.model = "Mustang"; cout << "Hello World!"; return 0;
carObj2.year = 1969; } }
// Print attribute values }; Parameters
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << int main() { You can also add parameters:
"\n"; MyClass myObj; // Create an object of MyClass Example
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << myObj.myMethod(); // Call the method #include <iostream>
"\n"; return 0; using namespace std;
return 0; } class Car {
} To define a function outside the class definition, you have to declare it inside public:
the class and then define it outside of the class. This is done by specifiying the int speed(int maxSpeed);
Constructor Parameters
// Create Car objects and call the constructor with different values brand = x;
Car carObj1("BMW", "X5", 1999); model = y;
Car carObj2("Ford", "Mustang", 1969); year = z;
Constructors can also take parameters (just like regular functions), which can be
// Print values }
useful for setting initial values for attributes.
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << int main() {
"\n"; // Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999); However, what if we want members to be private and hidden from the outside
Car carObj2("Ford", "Mustang", 1969); world? error: y is private
// Print values Note: It is possible to access private members of a class using a public method
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << In C++, there are three access specifiers: inside the same class. See the next chapter (Encapsulation) on how to do this.
"\n"; public - members are accessible from outside the class
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << private - members cannot be accessed (or viewed) from outside the class Tip: It is considered good practice to declare your class attributes as private (as
"\n"; protected - members cannot be accessed from outside the class, however, they often as you can). This will reduce the possibility of yourself (or others) to mess
return 0; can be accessed in inherited classes. You will learn more about Inheritance later. up the code. This is also the main ingredient of the Encapsulation concept,
} In the following example, we demonstrate the differences between public and which you will learn more about in the next chapter.
private members: Note: By default, all members of a class are private if you don't specify an access
};
// class members goes here
MyClass myObj; C++ Encapsulation
myObj.x = 25; // Allowed (public)
The public keyword is an access specifier. Access specifiers define how the Encapsulation
myObj.y = 50; // Not allowed (private)
members (attributes and methods) of a class can be accessed. In the example The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
return 0;
above, the members are public - which means that they can be accessed and from users. To achieve this, you must declare class variables/attributes as private
}
modified from outside the code. (cannot be accessed from outside the class). If you want others to read or modify
If you try to access a private member, an error occurs:
the value of a private member, you can provide public get and set methods.
}
Access Private Members Example explained In the example below, the Car class (child) inherits the attributes and methods
To access a private attribute, use public "get" and "set" methods: The salary attribute is private, which have restricted access. from the Vehicle class (parent):
Example The public setSalary() method takes a parameter (s) and assigns it to the salary Example
#include <iostream> attribute (salary = s). // Base class
using namespace std; The public getSalary() method returns the value of the private salary attribute. class Vehicle {
class Employee { Inside main(), we create an object of the Employee class. Now we can use the public:
private: setSalary() method to set the value of the private attribute to 50000. Then we call string brand = "Ford";
// Private attribute the getSalary() method on the object to return the value. void honk() {
int salary; cout << "Tuut, tuut! \n" ;
public: Why Encapsulation? }
// Setter It is considered good practice to declare your class attributes as private (as often };
void setSalary(int s) { as you can). Encapsulation ensures better control of your data, because you (or // Derived class
salary = s; others) can change one part of the code without affecting other parts class Car: public Vehicle {
} Increased security of data public:
// Getter string model = "Mustang";
int getSalary() {
C++ Inheritance
};
return salary; int main() {
} Car myCar;
Inheritance
}; myCar.honk();
In C++, it is possible to inherit attributes and methods from one class to
int main() { cout << myCar.brand + " " + myCar.model;
another. We group the "inheritance concept" into two categories:
Employee myObj; return 0;
myObj.setSalary(50000); }
derived class (child) - the class that inherits from another class
cout << myObj.getSalary(); Why And When To Use "Inheritance"?
base class (parent) - the class being inherited from
return 0;
To inherit from a class, use the : symbol.
C++ Polymorphism
void animalSound() { void animalSound() {
cout << "The pig says: wee wee \n"; cout << "The pig says: wee wee \n";
} }
Polymorphism
}; };
Polymorphism means "many forms", and it occurs when we have many classes
// Derived class // Derived class
that are related to each other by inheritance.
C++ Files
int main() { while (getline (MyReadFile, myText)) {
// Create and open a text file // Output the text from the file
ofstream MyFile("filename.txt"); cout << myText;
C++ Files
// Write to the file }
The fstream library allows us to work with files.
MyFile << "Files can be tricky, but it is fun enough!"; // Close the file
To use the fstream library, include both the standard <iostream> AND the
// Close the file MyReadFile.close();
<fstream> header file:
C++ Exceptions
} If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater
Consider the following example: than 18), the catch block is skipped:
C++ Exceptions
Example Example
When executing C++ code, different errors can occur: coding errors made by the
try { int age = 20;
programmer, errors due to wrong input, or other unforeseeable things.
int age = 15; You can also use the throw keyword to output a reference number, like a custom
When an error occurs, C++ will normally stop and generate an error message.
if (age >= 18) { error number/code for organizing purposes:
The technical term for this is: C++ will throw an exception (throw an error).
cout << "Access granted - you are old enough.";
} else { Example
C++ try and catch
throw (age); try {
Exception handling in C++ consist of three keywords: try, throw and catch:
} int age = 15;
The try statement allows you to define a block of code to be tested for errors
} if (age >= 18) {
while it is being executed.
catch (int myNum) { cout << "Access granted - you are old enough.";
The throw keyword throws an exception when a problem is detected, which lets
cout << "Access denied - You must be at least 18 years old.\n"; } else {
us create a custom error.
cout << "Age is: " << myNum; throw 505;
The catch statement allows you to define a block of code to be executed, if an
} }
error occurs in the try block.
Example explained }
The try and catch keywords come in pairs:
We use the try block to test some code: If the age variable is less than 18, we will catch (int myNum) {
throw an exception, and handle it in our catch block. cout << "Access denied - You must be at least 18 years old.\n";
Example
cout << "Error number: " << myNum;
try {
In the catch block, we catch the error and do something about it. The catch }
// Block of code to try
statement takes a parameter: in our example we use an int variable (myNum) Handle Any Type of Exceptions (...)
throw exception; // Throw an exception when a problem arise
(because we are throwing an exception of int type in the try block (age)), to If you do not know the throw type used in the try block, you can use the "three
}
output the value of age. dots" syntax (...) inside the catch block, which will handle any type of exception:
catch () {
not_eq An alternative way to write the != comparison operator true A boolean value equivalent to 1 acosh(x) Returns the hyperbolic arccosine of x
or An alternative way to write the logical || operator try Creates a try...catch statement asin(x) Returns the arcsine of x, in radians
or_eq An alternative way to write the |= assignment operator typedef Defines a custom data type asinh(x) Returns the hyperbolic arcsine of x
private An access modifier which makes a member onlyaccessible unsigned Specifies that an int or char should onlyrepresent positive values atan(x) Returns the arctangent of x as a numericvalue between
within the declared class which allows for storing numbers up to twice as large -PI/2 and PI/2 radians
protected An access modifier which makes a memberonly accessible using Allows variables and functions from a namespaceto be used atan2(y, x) Returns the angle theta from the conversionof
within the declared class and its children without the namespace's prefix rectangular coordinates (x, y) to polar coordinates (r, theta)
public An access modifier which makes a member accessible from virtual Specifies that a class method is virtual atanh(x) Returns the hyperbolic arctangent of x
anywhere void Indicates a function that does not return avalue or specifies a cbrt(x) Returns the cube root of x
return Used to return a value from a function pointer to a data with an unspecified type ceil(x) Returns the value of x rounded up to its nearest integer
short Reduces the size of an integer to 16 bits while Creates a while loop copysign(x, y) Returns the first floating point xwith the sign of the
signed Specifies that an int or char can representpositive and negative xor An alternative way to write the ^ bitwise operator second floating point y
values (this is the default so the keyword is not usually necessary) xor_eq An alternative way to write the ^= assignment operator cos(x) Returns the cosine of x (x is in radians)
sizeof An operator that returns the amount of memory occupied by a cosh(x) Returns the hyperbolic cosine of x
variable or data type
C++ Math Functions
exp(x) Returns the value of Ex
static Specifies that an attribute or method belongsto the class itself exp2(x) Returns the value of 2x
instead of instances of the classSpecifies that a variable in a function keeps its expm1(x) Returns ex-1
C++ Math Functions
value after the function ends erf(x) Returns the value of the error function at x
The <cmath> library has many functions that allow you to perform mathematical
struct Defines a structure erfc(x) Returns the value of the complementary error function at
tasks on numbers.
switch Selects one of many code blocks to be executed x
template Declares a template class or template function fabs(x) Returns the absolute value of a floating x
A list of all math functions can be found in the table below:
this A variable that is available inside class methodsand constructors fdim(x) Returns the positive difference between x and y
which contians a pointer to a class instance floor(x) Returns the value of x rounded down to its nearest integer
Function Description
throw Creates a custom error which can be caughtby a try...catch fma(x, y, z) Returns x*y+z without losing precision
abs(x) Returns the absolute value of x
statement fmax(x, y) Returns the highest value of a floating x and y
acos(x) Returns the arccosine of x, in radians
117 118