C++ Print
C++ Print
C++ Menu
Title pagenumber
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
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++ 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;
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
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
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:
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.
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
In the example below, we use the + operator to add together two values: - Subtraction Subtracts one value from another
Example 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
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";
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;
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
28 29
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
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.
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";
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
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.
52 53
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
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
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
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:
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 }
72 73
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]).
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
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
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
98 99
int main() { };
MyGrandChild myObj; // Derived class
myObj.myFunction(); class MyChildClass: public MyClass, public MyOtherClass {
return 0; };
} int main() {
MyChildClass myObj;
100 101
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 haveaccess 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 onlyaccessible unsigned Specifies that an int or char should onlyrepresent positive values
within the declared class which allows for storing numbers up to twice as large
protected An access modifier which makes a memberonly accessible using Allows variables and functions from a namespaceto 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 avalue 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 representpositive 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 belongsto 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 methodsand constructors
which contians a pointer to a class instance
Function Description
throw Creates a custom error which can be caughtby 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 thevalue of m (a value between
atan(x) Returns the arctangent of x as a numericvalue 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 conversionof underflow
rectangular coordinates (x, y) to polar coordinates (r, theta) ilogb(x) Returns the integer part of the floating-pointbase
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 valueof the gamma
copysign(x, y) Returns the first floating point xwith the sign of the function at x
second floating point y llrint(x) Rounds x to a nearby integer and returnsthe 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 logarithmof 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 returnsthe 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 returnsthe 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 pointnumber to x in the
direction of y
nexttoward(x, y) Returns the closest floating pointnumber 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 nearestinteger, 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