Vous êtes sur la page 1sur 36

SOLOLEARN

Data Types, Arrays, Pointers


Introduction to Data Types

Data Types
The operating system allocates memory and selects what will be stored in the reserved
memory based on the variable's data type.
The data type defines the proper use of an identifier, what kind of data can be stored, and
which types of operations can be performed.

There are a number of built-in types in C++.

„The difference between variable and identifier that is the identifier represent a name of a variable, In
another way each variable has a name, type and scope. The name of this variable called identifier.
Example: int number = 11; We declare a variable with name (identifier) number, with type int and
value 11.“

Data types are intended to define the proper use of an identifier.

Expressions
The examples below show legal and illegal C++ expressions.

55+15 // legal C++ expression


//Both operands of the + operator are integers

55 + "John" // illegal
// The + operator is not defined for integer and string

"Hello," + "John" // legal


// The + operator is used for string concatenation

„String concatenation is a programming term for attaching to "strings" together, think of it as a knot..
knotting a word together, or a sentence, or a sequence of alphanumeric (yes that was a leap in detail,
but pretty necessary to understand the concept of concatenating) in a job interview, I was once asked
to concatenate a set of characters from bangfizz to fizzbang, which is complicated since it relies on
counting the chars rather than searching for "fizz" or "bang".. (a char is char c = 'c' or char ch = 50 //
prints the number 2 as a character.... be very charful (haha) with how you proceed with
concatenation as it can tag along alot of messy code and errors...“
SOLOLEARN
Numeric Data Types
Numeric data types include:
Integers (whole numbers), such as -7, 42.
Floating point numbers, such as 3.14, -42.67.

Strings & Characters


A string is composed of numbers, characters, or symbols. String literals are placed in double
quotation marks; some examples are "Hello", "My name is David", and similar.

Characters are single letters or symbols, and must be enclosed between single quotes, like
'a', 'b', etc.

In C++, single quotation marks indicate a character; double quotes create a string literal.
While 'a' is a single a character literal, "a" is a string literal.

Booleans
The Boolean data type returns just two possible values: true (1) and false (0).
Conditional expressions are an example of Boolean data type.
SOLOLEARN
Integers
The integer type holds non-fractional numbers, which can be positive or negative. Examples
of integers would include 42, -42, and similar numbers.

The size of the integer type varies according to the architecture of the system on which the
program runs, although 4 bytes is the minimum size in most modern system architectures.

Use the int keyword to define the integer data type.

int a = 42;
Several of the basic types, including integers, can be modified using one or more of these type
modifiers:
signed: A signed integer can hold both negative and positive numbers.
unsigned: An unsigned integer can hold only positive values.
short: Half of the default size.
long: Twice the default size.

For example:
unsigned long int a;

Floating Point Numbers


A floating point type variable can hold a real number, such as 420.0, -3.33, or 0.03325.
The words floating point refer to the fact that a varying number of digits can appear before
and after the decimal point. You could say that the decimal has the ability to "float".

There are three different floating point data types: float, double, and long double.

In most modern architectures, a float is 4 bytes, a double is 8, and a long double can be
equivalent to a double (8 bytes), or 16 bytes.

For example: double temp = 4.21;

Floating point data types are always signed, which means that they have the capability
to hold both positive and negative values.
SOLOLEARN
Strings
A string is an ordered sequence of characters, enclosed in double quotation marks.
It is part of the Standard Library.
You need to include the <string> library to use the string data type. Alternatively, you can
use a library that includes the string library.

#include <string>
using namespace std;
int main() {
string a = "I am learning C++";
return 0;
}

The <string> library is included in the <iostream> library, so you don't need to include <string>
separately, if you already use <iostream>.

comments
„actually, <iostream> and <string> are not the same, you must include <string> even you had already
included <iostream> before if you want to use the string type.“

A string may hold something with at least 1 character or nothing at all.


A space is considered to be 1 character.
A string will hold anything that is in double quotation marks. You can't use single quotation marks.
You can't store numbers in string like:
string a = 10;
However, you can do:
string a = "10";
but you can't really use it to calculate numbers.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "10";
string b = "15";
cout << a << endl;
cout << b << endl;
cout << a + b << endl;
cout << a << b;
}
//outputs 10, 15, 1015, 1015
When you add the string a with string b, you get 1015 instead of 25. This is what I meant by you can't
really use it to calculate numbers.
SOLOLEARN
Characters
A char variable holds a 1-byte integer. However, instead of interpreting the value of the char
as an integer, the value of a char variable is typically interpreted as an ASCII character.

A character is enclosed between single quotes (such as 'a', 'b', etc).


For example:

char test = 'S';

American Standard Code for Information Interchange (ASCII) is a character-encoding


scheme that is used to represent text in computers.

Comments
A char can only hold single characters.
A space is a single character.
Characters are letters, numbers, special characters and spaces.

You can add string types, but you can't add char types.
char x = 'h';
char y = 'i';
cout << x + y; //you can't do this, but you can do this :
cout << x << y;
//outputs hi

char letter= 115;


cout << letter;
// Outputs: s

Booleans
Boolean variables only have two possible values: true (1) and false (0).
To declare a boolean variable, we use the keyword bool.

bool online = false;


bool logged_in = true;

If a Boolean value is assigned to an integer, true becomes 1 and false becomes 0.


If an integer value is assigned to a Boolean, 0 becomes false and any value that has a non-zero
value becomes true.
SOLOLEARN
Variable Naming Rules
Use the following rules when naming variables:
- All variable names must begin with a letter of the alphabet or an underscore( _ ).
- After the initial letter, variable names can contain additional letters, as well as numbers.
Blank spaces or special characters are not allowed in variable names.

There are two known naming conventions:


Pascal case: The first letter in the identifier and the first letter of each subsequent
concatenated word are capitalized. For example: BackColor
Camel case: The first letter of an identifier is lowercase and the first letter of each subsequent
concatenated word is capitalized. For example: backColor

Case-Sensitivity
C++ is case-sensitive, which means that an identifier written in uppercase is not equivalent to
another one with the same name in lowercase.
For example, myvariable is not the same as MYVARIABLE and not the same as MyVariable.
These are three different variables.

Choose variable names that suggest the usage, for example: firstName, lastName.

Variable Naming Rules


C++ keyword (reserved word) cannot be used as variable names.
For example, int, float, double, cout cannot be used as a variable name.

There is no real limit on the length of the variable name (depends on the environment), but try
to keep your variable names practical and meaningful.
SOLOLEARN
Arrays
An array is used to store a collection of data, but it may be useful to think of an array as a
collection of variables that are all of the same type.
Instead of declaring multiple variables and storing individual values, you can declare a single
array to store all the values.
When declaring an array, specify its element types, as well as the number of elements it will
hold.
For example:
int a[5];
In the example above, variable a was declared as an array of five integer values [specified in
square brackets].
You can initialize the array by specifying the values it holds:
int b[5] = {11, 45, 62, 70, 88};
The values are provided in a comma separated list, enclosed in {curly braces}.

The number of values between braces { } must not exceed the number of the elements declared
within the square brackets [ ].

Initializing Arrays
If you omit the size of the array, an array just big enough to hold the initialization is created.
For example:

int b[] = {11, 45, 62, 70, 88};

This creates an identical array to the one created in the previous example.
Each element, or member, of the array has an index, which pinpoints the element's specific
position.
The array's first member has the index of 0, the second has the index of 1.
So, for the array b that we declared above:
SOLOLEARN
To access array elements, index the array name by placing the element's index in square
brackets following the array name.
For example:
int b[] = {11, 45, 62, 70, 88};

cout << b[0] << endl;


// Outputs 11

cout<< b[3] << endl;


// Outputs 70

Accessing Array Elements


Index numbers may also be used to assign a new value to an element.

int b[] = {11, 45, 62, 70, 88};


b[2] = 42;

This assigns a value of 42 to the array's third element.

Always remember that the list of elements always begins with the index of 0.

comments
Normally, the size of an array must be known when the program is compiled. This means that your
program can’t ask the user for a size to put into a variable and then create an array of that size:

cin >> size;

int array[size]; // THIS WON’T WORK!

You must hard code the size of your array prior as shown below. Here are some ways you can define
an array:

int array1[ ] = { 12, 2, 28 }; // this will create and initialize an array of 3 elements

const int SIZE = 10;

int array2[SIZE] = { 0 }; // this will create an array of 10 elements and set them all to 0

int array3[SIZE] = { 7 }; // this will initialize only the first element in the array to 7, and the remaining
elements will automatically be set to 0

int array4[SIZE] = { 5, 6, 7 }; // this will set the first 3 elements to 5, 6, 7, and the remaining elements
will be set to 0
SOLOLEARN

int array5[SIZE]; // This will not initialize any of the elements in the array. With no initialization, all
elements in the array will have random values (whatever was stored in those memory locations from
some other program) until you overwrite them by assigning meaningful values to your array.

Char arrays and c-strings:

char array6[SIZE] = “Fred”; // this will place the 5 characters F r e d \0 into the first 5 elements of the
array; the zero terminator ‘\0’ automatically placed at the end creates a c-string

char array7[ ] = “Fred”; // same as above except the array will just be 5 elements long instead of 10
which was stored in the SIZE value

char array8[SIZE] = { 'F', 'r', 'e', 'd' }; // This will place the characters F r e d (without a null character
\0 at the end) into the first 4 elements of the array. Without the null character at the end it is not a c-
string.

What is the significance of a c-string? If a character array is terminated by a \0 (null character), thus
making it a c-string, you can output the full c-string easily by just using the variable name without the
element brackets [ ]:

char salutation[ ] = “Hey. How’s it going?”

cout << salutation; // will output the full c-string instead of just a single element: Hey. How's it
going?

Feel free to add any additional C++ array tips that you think are helpful!

Arrays in Loops
It's occasionally necessary to iterate over the elements of an array, assigning the elements
values based on certain calculations.

Usually, this is accomplished using a loop.

Arrays in Loops
Let's declare an array, that is going to store 5 integers, and assign a value to each element
using the for loop:

int myArr[5];
for(int x=0; x<5; x++) {
myArr[x] = 42;
}
SOLOLEARN
Each element in the array is assigned the value of 42.
The x variable in the for loop is used as the index for the array.

The last index in the array is 4, so the for loop condition is x<5.

comments
int apples[5];
This means that there 5 elements in this array.
apples[0], apples[1], apples[2], apples[3], apples[4]
for (int x = 0; x < 5; x++)
{
apples[x] = 42;
}
The apples[x] refers to the position of the array or the index of the array. We initialized x to start at
0, so we begin with apples[0] = 42. Then the x is incremented by 1 and the loop keeps going until all
the elements have 42 stored in them.

Arrays in Loops
Let's output each index and corresponding value in the array.

int myArr[5];

for(int x=0; x<5; x++) {


myArr[x] = 42;
cout << x << ": " << myArr[x] << endl;
}

/* Outputs
0: 42
1: 42
2: 42
3: 42
4: 42
*/
SOLOLEARN
Arrays in Calculations
The following code creates a program that uses a for loop to calculate the sum of all elements
of an array.

int arr[] = {11, 35, 62, 555, 989};


int sum = 0;

for (int x = 0; x < 5; x++) {


sum += arr[x];
}

cout << sum << endl;


//Outputs 1652

To review, we declared an array and a variable sum that will hold the sum of the elements.
Next, we utilized a for loop to iterate through each element of the array, and added the
corresponding element's value to our sum variable.

In the array, the first element's index is 0, so the for loop initializes the x variable to 0.

Multi-Dimensional Arrays
A multi-dimensional array holds one or more arrays. Declare a multidimensional array as
follows.
type name[size1][size2]...[sizeN];

Here, we've created a two-dimensional 3x4 integer array:


int x[3][4];
Visualize this array as a table composed of 3 rows, and 4 columns.
SOLOLEARN
Two-Dimensional Arrays
Multi-dimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 2 rows and 3 columns:

int x[2][3] = {
{2, 3, 4}, // 1st row
{8, 9, 10} // 2nd row
};

You can also write the same initialization using just one row.

int x[2][3] = {{2, 3, 4}, {8, 9, 10}};

The elements are accessed by using the row index and column index of the array.
For example:

int x[2][3] = {{2, 3, 4}, {8, 9, 10}};


cout << x[0][2] << endl; //Outputs 4

The first index 0 refers to the first row. The second index 2 refers to the 3rd element of the first row,
which is 4.

Multi-Dimensional Arrays
Arrays can contain an unlimited number of dimensions.
string threeD[42][8][3];
The example above declares a three-dimensional array of strings. As we did previously, it's
possible to use index numbers to access and modify the elements.

Arrays more than three dimensions are harder to manage.

Comments
array[2][3] = 2 arrays containing 3 values each - { {1,2,3}, {1,2,3} }

array[2][3][4] = 2 arrays containing 3 arrays each containing 4 values each - { { {1,2,3,4}, {1,2,3,4},
{1,2,3,4} }, { {1,2,3,4}, {1,2,3,4}, {1,2,3,4} } }
SOLOLEARN
to go through the three dimensional array with for loop

string arraythreeD[2][3][4] = { { {"1","2","3","4"}, {"5","6","7","8"}, {"9","10","11","12"} }, {


{"13","14","15","16"}, {"17","18","19","20"}, {"21","22","23","24"} } };
for (int x=0;x<2;x++)
{
for (int y=0;y<3;y++)
{
for (int z=0;z<4;z++)
{
cout << arraythreeD[x][y][z] << " ";
}
cout << endl;
}
cout << endl;
}
SOLOLEARN
Introduction to Pointers

Pointers
Every variable is a memory location, which has its address defined.
That address can be accessed using the ampersand (&) operator (also called the address-of
operator), which denotes an address in memory.

For example:

int score = 5;
cout << &score << endl;

//Outputs "0x29fee8"

This outputs the memory address, which stores the variable score.

Pointers
A pointer is a variable, with the address of another variable as its value.
In C++, pointers help make certain tasks easier to perform. Other tasks, such as dynamic
memory allocation, cannot be performed without using pointers.

All pointers share the same data type - a long hexadecimal number that represents a memory
address.
The only difference between pointers of different data types is the data type of the variable
that the pointer points to.

Pointers
A pointer is a variable, and like any other variable, it must be declared before you can work
with it.
The asterisk sign is used to declare a pointer (the same asterisk that you use for
multiplication), however, in this statement the asterisk is being used to designate a variable as
a pointer.
Following are valid pointer declarations:

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to a character7

Just like with variables, we give the pointers a name and define the type, to which the pointer
points to.

The asterisk sign can be placed next to the data type, or the variable name, or in the middle.
SOLOLEARN
Using Pointers
Here, we assign the address of a variable to the pointer.

int score = 5;
int *scorePtr;
scorePtr = &score;

cout << scorePtr << endl;

//Outputs "0x29fee8"

The code above declares a pointer to an integer called scorePtr, and assigns to it the memory
location of the score variable using the ampersand (address-of) operator.
Now, scorePtr's value is the memory location of score.

Pointer Operations
There are two operators for pointers:
Address-of operator (&): returns the memory address of its operand.
Contents-of (or dereference) operator (*): returns the value of the variable located at the
address specified by its operand.

For example:

int var = 50;


int *p;
p = &var;

cout << var << endl;


// Outputs 50 (the value of var)

cout << p << endl;


// Outputs 0x29fee8 (var's memory location)

cout << *p << endl;


/* Outputs 50 (the value of the variable stored in the pointer p) */

The asterisk (*) is used in declaring a pointer for the simple purpose of indicating that it is a pointer
(The asterisk is part of its type compound specifier). Don't confuse this with the dereference
operator, which is used to obtain the value located at the specified address. They are simply two
different things represented with the same sign.
SOLOLEARN
Dereferencing
The dereference operator (*) is basically an alias for the variable the pointer points to.
For example:
int x = 5;
int *p = &x;
x = x + 4;
x = *p + 4;
*p = *p + 4;

All three of the preceding statements are equivalent, and return the same result. We can access
the variable by dereferencing the variable's pointer.

As p is pointing to the variable x, dereferencing the pointer (*p) is representing exactly the
same as the variable x.
Primjer 1:
int main()
{
int x = 5;
int *p = &x;
x = x + 4;
cout<<"x=x+4 =>"<<x<<endl; //outputs 9
cout<<"*p =>"<<*p<<endl; //outputs 9
x = *p + 4;
cout<<"x=*p+4 =>"<<x<<endl; //outputs 13
cout<<"*p =>"<<*p<<endl; //outputs 13
*p = *p + 4;
cout<<"*p=*p+4 =>"<<*p<<endl; //outputs 17
cout<<"x =>"<<x<<endl; //outputs 17
cout<<"*p =>"<<*p<<endl; //outputs 17
}

Primjer 2:
int main() {
int x = 5;
int *p = &x;
x = x + 4;
cout<<"x : "<<x<<endl; // outputs 9
cout<<"*p : "<<*p<<endl; // outputs 9
x = *p + 4;
cout<<"*p : "<<*p<<endl; //outputs 13
cout<<"x :"<<x<<endl; //outputs 13
*p = *p + 4;
cout<<"*p :"<<*p<<endl; //outputs 17
}
SOLOLEARN
Static & Dynamic Memory
To be successful as a C++ programmer, it's essential to have a good understanding of how
dynamic memory works.
In a C++ program, memory is divided into two parts:
The stack: All of your local variables take up memory from the stack.
The heap: Unused program memory that can be used when the program runs to dynamically
allocate the memory.

Many times, you are not aware in advance how much memory you will need to store
particular information in a defined variable and the size of required memory can be
determined at run time.
You can allocate memory at run time within the heap for the variable of a given type using the
new operator, which returns the address of the space allocated.

new int;

This allocates the memory size necessary for storing an integer on the heap, and returns that
address.

Comments
Dynamic memory is allocated on the "heap". The heap is the region of computer memory which is
managed by the programmer using pointers to access the memory.
Heap memory details:
-can be accessed globally
-your limit is the physical memory limit of your system (real and virtual)
-user managed memory. Programmer must allocate and free memory.
-memory access is via pointer and thus requires dereferencing to access, requiring extra operations
and time
-memory can become defragmented as memory is allocated and freed
-memory can be resized (eg using realloc())
The "stack" is the region of memory which stores declared variables in main() and all called
functions. When a function returns, the memory space for the declared variables is released
("popped"). The stack is FILO (first in - lst out) and unwinds variables in memory as functions return.
-the "stack" grows and shrinks as functions push and pop local variables
-the "stack" is managed by t

When should you use the heap, and when should you use the stack?
If you need to allocate a large block of memory (e.g. a large array, or a big struct), and you need to
keep that variable around a long time (like a global), then you should allocate it on the heap.
SOLOLEARN
If you are dealing with realtively small variables that only need to persist as long as the function
using them is alive, then you should use the stack, it's easier and faster.

Dynamic Memory
The allocated address can be stored in a pointer, which can then be dereferenced to access the
variable.
Example:

int *p = new int;


*p = 5;

We have dynamically allocated memory for an integer, and assigned it a value of 5.

The pointer p is stored in the stack as a local variable, and holds the heap's allocated address
as its value. The value of 5 is stored at that address in the heap.
SOLOLEARN
Dynamic Memory
For local variables on the stack, managing memory is carried out automatically.
On the heap, it's necessary to manually handle the dynamically allocated memory, and use the
delete operator to free up the memory when it's no longer needed.

delete pointer;

This statement releases the memory pointed to by pointer.

For example:

int *p = new int; // request memory


*p = 5; // store value

cout << *p << endl; // use value

delete p; // free up the memory

Forgetting to free up memory that has been allocated with the new keyword will result in memory
leaks, because that memory will stay allocated until the program shuts down.

Dangling Pointers
The delete operator frees up the memory allocated for the variable, but does not delete the
pointer itself, as the pointer is stored on the stack.

Pointers that are left pointing to non-existent memory locations are called dangling pointers.
For example:

int *p = new int; // request memory


*p = 5; // store value

delete p; // free up the memory


// now p is a dangling pointer

p = new int; // reuse for a new address

The NULL pointer is a constant with a value of zero that is defined in several of the standard libraries,
including iostream. It's a good practice to assign NULL to a pointer variable when you declare it, in
case you do not have exact address to be assigned. A pointer assigned NULL is called a null pointer.
For example: int *ptr = NULL;
SOLOLEARN
Dynamic Memory
Dynamic memory can also be allocated for arrays.
For example:

int *p = NULL; // Pointer initialized with null


p = new int[20]; // Request memory
delete [] p; // Delete array pointed to by p

Note the brackets in the syntax.

Dynamic memory allocation is useful in many situations, such as when your program depends
on input. As an example, when your program needs to read an image file, it doesn't know in
advance the size of the image file and the memory necessary to store the image.
SOLOLEARN
sizeof
While the size allocated for varying data types depends on the architecture of the computer you use
to run your programs, C++ does guarantee a minimum size for the basic data types:

The sizeof operator can be used to get a variable or data type's size, in bytes.
Syntax: sizeof (data type)
The sizeof operator determines and returns the size of either a type or a variable in bytes.
For example:

cout << "char: " << sizeof(char) << endl;


cout << "int: " << sizeof(int) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "double: " << sizeof(double) << endl;
int var = 50;
cout << "var: " << sizeof(var) << endl;

/* Outputs
char: 1
int: 4
float: 4
double: 8
var: 4
*/
Output values may vary, according to the computer and compiler used.
SOLOLEARN
Size of an Array
The C++ sizeof operator is also used to determine the size of an array.
For example:

double myArr[10];
cout << sizeof(myArr) << endl;

//Outputs 80

On our machine, double takes 8 bytes. The array stores 10 doubles, so the entire array occupies 80
(8*10) bytes in the memory.

In addition, divide the total number of bytes in the array by the number of bytes in a single element
to learn how many elements you have in the array.
For example:

int numbers[100];
cout << sizeof(numbers) / sizeof(numbers[0]);

// Outputs 100

Functions
A function is a group of statements that perform a particular task.
You may define your own functions in C++.

Using functions can have many advantages, including the following:


- You can reuse the code within a function.
- You can easily test individual functions.
- If it's necessary to make any code modifications, you can make modifications within a single
function, without altering the program structure.
- You can use the same function for different inputs.

Every valid C++ program has at least one function - the main() function.
SOLOLEARN
The Return Type
The main function takes the following general form:
int main(){
// some code
return 0;
}

A function's return type is declared before its name. In the example above, the return type is
int, which indicates that the function returns an integer value.
Occasionally, a function will perform the desired operations without returning a value. Such
functions are defined with the keyword void.

void is a basic data type that defines a valueless state.

Defining a Function
Define a C++ function using the following syntax:
return_type function_name( parameter list )
{
body of the function
}

return-type: Data type of the value returned by the function.


function name: Name of the function.
parameters: When a function is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function.
body of the function: A collection of statements defining what the function does.

Parameters are optional; that is, you can have a function with no parameters.

Defining a Function
As an example, let's define a function that does not return a value, and just prints a line of text
to the screen.
void printSomething()
{
cout << "Hi there!";
}

Our function, entitled printSomething, returns void, and has no parameters.


Now, we can use our function in main().
int main() {
printSomething();
return 0;
}
SOLOLEARN
To call a function, you simply need to pass the required parameters along with the function name.

Functions
You must declare a function prior to calling it.
For example:
#include <iostream>
using namespace std;
void printSomething() {
cout << "Hi there!";
}

int main() {
printSomething();
return 0;
}

Putting the declaration after the main() function results in an error.

Functions
A function declaration, or function prototype, tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately.
For example:
#include <iostream>
using namespace std;

//Function declaration
void printSomething();

int main() {
printSomething();
return 0;
}

//Function definition
void printSomething() {
cout << "Hi there!";
}
SOLOLEARN
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling the
function.

Function Parameters
For a function to use arguments, it must declare formal parameters, which are variables that
accept the argument's values.

For example:
void printSomething(int x)
{
cout << x;
}

This defines a function that takes one integer parameter and prints its value.

Formal parameters behave within the function similarly to other local variables. They are
created upon entering the function, and are destroyed upon exiting the function.

Function Parameters
Once parameters have been defined, you can pass the corresponding arguments when the function
is called.
For example:
#include <iostream>
using namespace std;
void printSomething(int x) {
cout << x;
}
int main() {
printSomething(42);
}
// Outputs 42

The value 42 is passed to the function as an argument, and is assigned to the formal parameter of
the function: x.

Making changes to the parameter within the function does not alter the argument.
SOLOLEARN
Function Parameters
You can pass different arguments to the same function.
For example:
int timesTwo(int x) {
return x*2;
}

The function defined above takes one integer parameter and returns its value, multiplied by 2.

We can now use that function with different arguments.


int main() {
cout << timesTwo(8);
// Outputs 16

cout <<timesTwo(5);
// Outputs 10

cout <<timesTwo(42);
// Outputs 84
}

Multiple Parameters
You can define as many parameters as you want for your functions, by separating them with
commas.
Let's create a simple function that returns the sum of two parameters.

int addNumbers(int x, int y) {


// code goes here
}

As defined, the addNumbers function takes two parameters of type int, and returns int.

Data type and name should be defined for each parameter.

Multiple Parameters
Now let's calculate the sum of the two parameters and return the result:

int addNumbers(int x, int y) {


int result = x + y;
return result;
}
SOLOLEARN
Multiple Parameters
Now we can call the function.
int addNumbers(int x, int y) {
int result = x + y;
return result;
}

int main() {
cout << addNumbers(50, 25);
// Outputs 75
}

You can also assign the returned value to a variable.

int main() {
int x = addNumbers(35, 7);
cout << x;
// Outputs 42
}

Multiple Parameters
You can add as many parameters to a single function as you want.
For example:
int addNumbers(int x, int y, int z, int a) {
int result = x + y + z + a;
return result;
}
If you have multiple parameters, remember to separate them with commas, both when declaring
them and when passing the arguments.
SOLOLEARN
Random Numbers
Being able to generate random numbers is helpful in a number of situations, including when creating
games, statistical modeling programs, and similar end products.

In the C++ standard library, you can access a pseudo random number generator function that's called
rand(). When used, we are required to include the header <cstdlib>.
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
cout << rand();
}

This will output a random number.

Random Numbers
A for loop can be used to generate multiple random numbers.
int main() {
for (int x = 1; x <= 10; x++) {
cout << rand() << endl;
}
}

/* Output:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
*/
SOLOLEARN
Random Numbers
Use the modulo (%) operator to generate random numbers within a specific range.
The example below generates whole numbers within a range of 1 to 6.
int main () {
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 6) << endl;
}
}

/* Output:
6
6
5
5
6
5
1
1
5
3
*/

However, the rand() function will only return a pseudo random number. This means that each time
the code is run, it generates the same numbers.

Print a random number from 1 through 9:


cout << 1 + ( rand() % 9 ) << endl;

comments

This functions cannot be compared with true randomness. Even though the rand() and srand()
functions seem to do a great job simulating randomness, they are deterministic and therefore if the
seed and algorithm are known, then the output is also known. Also, after some time, the sequence
will start to show the same pattern, no matter what input you give. Bigger seeds give you longer
sequences, but it will still repeat itself. The advantage of srand() functions is that they allow to
transform a small number into a long seemingly random sequence. So, if you're going to implement
this functions, you must know if it swits your purposes.
SOLOLEARN
Truly Random Numbers
A solution to generate truly random numbers, is to use the current time as a seed value for the
srand() function.
This example makes use of the time() function to get the number of seconds on your system time,
and randomly seed the rand() function (we need to include the <ctime> header for it):
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main () {
srand(time(0));
for (int x = 1; x <= 10; x++) {
cout << 1 + (rand() % 6) << endl;
}
}

time(0) will return the current second count, prompting the srand() function to set a different seed
for the rand() function each time the program runs.

Using this seed value will create a different output each time we run the program.

Default Values for Parameters


When defining a function, you can specify a default value for each of the last parameters. If the
corresponding argument is missing when you call a function, it uses the default value.

To do this, use the assignment operator to assign values to the arguments in the function definition,
as shown in this example.
int sum(int a, int b=42) {
int result = a + b;
return (result);
}

This assigns a default value of 42 to the b parameter. If we call the function without passing the value
for the b parameter, the default value will be used.
int main() {
int x = 24;
int y = 36;

//calling the function with both parameters


SOLOLEARN
int result = sum(x, y);
cout << result << endl;
//Outputs 60

//calling the function without b


result = sum(x);
cout << result << endl;
//Outputs 66

return 0;
}

The second call to the function does not pass a value for the second parameter, and the default value
of 42 is used, instead.

Using Default Arguments


Another example:
int volume(int l=1, int w=1, int h=1) {
return l*w*h;
}

int main() {
cout << volume() << endl;
cout << volume(5) << endl;
cout << volume(2, 3) << endl;
cout << volume(3, 7, 6) << endl;
}

/* Output
1
5
6
126
*/

As you can see, default parameter values can be used for calling the same function in different
situations, when one or more of its parameters are not used.
SOLOLEARN
What is the output of the following code?

void printSum(int a, int b = 4)


{
cout << a + b << endl;
}
int main()
{
printSum(13); //outputs 17
}

Overloading
Function overloading allows to create multiple functions with the same name, so long as
they have different parameters.

For example, you might need a printNumber() function that prints the value of its parameter.

void printNumber(int a) {
cout << a;
}

This is effective with integer arguments only. Overloading it will make it available for other
types, such as floats.

void printNumber(float a) {
cout << a;
}

Now, the same printNumber() function name will work for both integers and floats.

Comments

Overloading here means Loading something new Over an already existing one. So both exist. It is not
same as overwriting or overriding.
If there is a function which was declared two (or more) times with different number of parameters
(or types of parameters), just consider it as two different functions which have just the same name.
For example,
int CalculateAreaOfTriangle (int x1, int y1, int x2, int y2, int x3, int y3);
// this is to calculate the area of triangle with 3 coordinators.

int CalculateAreaOfTriangle (int height, int width);


// this is to calculate the area of triangle with height and width.
SOLOLEARN
The purposes of both functions are same hence it is convenient to name them same as
"CalculateAreaOfTriangle" (it is easy to remember!) You can use it later for both cases where you
have either coordinators or height & width.

Function Overloading
When overloading functions, the definition of the function must differ from each other by the types
and/or the number of arguments in the argument list.
For example:
void printNumber(int x) {
cout << "Prints an integer: " << x << endl;
}
void printNumber(float x) {
cout << "Prints a float: " << x << endl;
}
int main() {
int a = 16;
float b = 54.541;
printNumber(a);
printNumber(b);
}

/* Output:
Prints an integer: 16
Prints a float: 54.541
*/

As you can see, the function call is based on the argument provided. An integer argument will call
the function implementation that takes an integer parameter. A float argument will call the
implementation taking a float parameter.

Function Overloading
You can not overload function declarations that differ only by return type.
The following declaration results in an error.

int printName(int a) { }
float printName(int b) { }
double printName(int c) { }
Although each function uses the same name, the only difference from one to the other is the return
type, which is not allowed.
SOLOLEARN
Recursion
A recursive function in C++ is a function that calls itself.
To avoid having the recursion run indefinitely, you must include a termination condition.

To demonstrate recursion, let's create a program to calculate a number's factorial.


In mathematics, the term factorial refers to the product of all positive integers that are less
than or equal to a specific non-negative integer (n). The factorial of n is denoted as n!
For example:

4! = 4 * 3 * 2 * 1 = 24

Comment

if you need to write recursive function you should determine three steps
1-Recursive call function (Digging function)
2-Stop Condition
3-in recursive function lead to stop condition
this example can explain three steps (Factorial of number)
#include<iostream>
using namespace std;
int factorial(int n) {
if(n==1 || n==0) // stop condition
return 1;
return n*factorial(n-1); // recursive call function and lead to stop condition
}
int main()
{
int n;
cin>>n;
cout<<"Factorial of "<<n<<" is " <<factorial(n)<<endl;
return 0;
}
test this code: number 5
factorial(5)=5*factorial(4);
factorial(4)=4*factorial(3);
factorial(3)=3*factorial(2);
factorial(2)=2*factorial(1);
factorial(5)=1; //stop and return to solve the last call function
then
factorial(2)=2*1;
factorial(3)=3*2;
factorial(4)=4*6;
factorial(5)=5*24=120;
and return to main function Important note: if we write factorial(n+1) this lead to the stop condition
is not true so this lead to infi
SOLOLEARN
Recursion
Let's define our function:

int factorial(int n) {
if (n==1) {
return 1;
}
else {
return n * factorial(n-1);
}
}

The if statement defines the exit condition. In this case, it's when n equals one, return 1 (the
factorial of one is one).
We placed the recursive function call in the else statement, which returns n multiplied by the
factorial of n-1.
For example, if you call the factorial function with the argument 4, it will execute as follows:
return 4 * factorial(3), which is 4*3*factorial(2), which is 4*3*2*factorial(1), which is
4*3*2*1.

The factorial function calls itself, and then continues to do so, until the argument equals 1.

Recursion
We're now at the point where we can call our factorial function.
int factorial(int n)
{
if (n==1) {
return 1;
}
else {
return n * factorial(n-1);
}
}
int main() {
cout << factorial(5);
}
//Outputs 120
Another name for the exit condition is the base case.
Keep in mind that a base case is necessary for real recursion. Without it, the recursion will keep
running forever.
SOLOLEARN
Functions
Passing Arrays to Functions
Arrays and Functions
An array can also be passed to a function as an argument.
The parameter should be defined as an array using square brackets, when declaring the
function.
For example:
void printArray(int arr[], int size) {
for(int x=0; x<size; x++) {
cout <<arr[x];
}
}

Vous aimerez peut-être aussi