Day 1 - Functions and Array

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 35

Day 1 – Functions & Arrays

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

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"


• A function can be called multiple times:
Example
void myFunction()
{
cout << "I just got executed!\n";
}

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

// I just got executed!


// I just got executed!
// I just got executed!
Function Declaration and Definition

A C++ function consist of two parts:


• Declaration: the function's name, return type,
and parameters (if any)
• Definition: the body of the function (code to be
executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
• Note: If a user-defined function, such as myFunction() is declared after
the main() function, an error will occur. It is because C++ works from top to
bottom; which means that if the function is not declared above main(), the
program is unaware of it:
int main()
{
myFunction();
return 0;
}
void myFunction()
{
cout << "I just got executed!";
}

// Error
• However, it is possible to separate the declaration and the definition of the function - for
code optimization.
• You will often see C++ programs that have function declaration above main(), and function
definition below main()
• // Function declaration

void myFunction();

// The main method


int main()
{
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction()
{
cout << "I just got executed!";
}
C++ Function Parameters
• Parameters and Arguments
• Information can be passed to functions as a parameter.
Parameters act as variables inside the function.
• Parameters are specified after the function name, inside the
parentheses. You can add as many parameters as you want,
just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example
void myFunction(string fname)
{
cout << fname << " Refsnes\n";
}

int main()
{
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Output
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the function, it is called an argument. So, from the example above: fname is
a parameter, while Liam, Jenny and Anja are arguments.
Default Parameter Value
• You can also use a default parameter value, by using the equals sign (=).
Example
void myFunction(string country = "Norway")
{
cout << country << "\n";
}

int main()
{
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}

// Sweden
// India
// Norway
// USA
C++ Multiple Parameters
• Inside the function, you can add as many parameters as you want:
• Example
void myFunction(string fname, int age)
{
cout << fname << " Refsnes. " << age << " years old. \n";
}

int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Liam Refsnes. 3 years old.


// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are
parameters, and the arguments must be passed in the same order.
C++ The Return Keyword
Return Values
The void keyword, used in the previous examples, indicates that the function should
not return a value. If you want the function to return a value, you can use a data type
(such as int, string, etc.) instead of void, and use the return keyword inside the
function:
Example
int myFunction(int x)
{
return 5 + x;
}

int main()
{
cout << myFunction(3);
return 0;
}

// Outputs 8
Example
This example returns the sum of a function with two parameters:

int myFunction(int x, int y)


{
return x + y;
}

int main()
{
cout << myFunction(5, 3);
return 0;
}

// Output 8
Example - You can also store the result in a variable:

int myFunction(int x, int y)


{
return x + y;
}

int main()
{
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Call Type & Description
• Call by Value This method copies the actual value of an argument into
the formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.
• Call by (address) Pointer This method copies the address of an
argument into the formal parameter. Inside the function, the address
is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
• Call by Reference This method copies the reference of an argument
into the formal parameter. Inside the function, the reference is used
to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
C++ function Call by value
• The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function. In this case,
changes made to the parameter inside the function
have no effect on the argument.

• By default, C++ uses call by value to pass arguments.


C++ function Call by value
#include <iostream.h>
// function declaration void swap(int x,int y)
void swap(int x, int y); {
int t;
int main ()
{
t=x;
// local variable declaration: x=y;
int a = 100; y=t;
int b = 200;
}
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values. Before swap, value of a :100


swap(a, b); Before swap, value of b :200
After swap, value of a :100
cout << "After swap, value of a :" << a << endl; After swap, value of b :200
cout << "After swap, value of b :" << b << endl;
Which shows that there is no change in
return 0;
}
the values though they had been
changed inside the function.
C++ function Call by pointer
• The call by pointer method of passing
arguments to a function copies the address of
an argument into the formal parameter. Inside
the function, the address is used to access the
actual argument used in the call. This means
that changes made to the parameter affect
the passed argument.
using namespace std;
// function definition to swap the values.
void swap(int *x, int *y)
// function declaration {
void swap(int *x, int *y); int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
int main () *y = temp; /* put x into y */
{
return;
// local variable declaration: }
int a = 100;

int b = 200;

When the above code is put


together in a file, compiled and
cout << "Before swap, value of a :" << a << endl;
executed, it produces the following
cout << "Before swap, value of b :" << b << endl; result −
Before swap, value of a :100
Before swap, value of b :200
/* calling a function to swap the values.
After swap, value of a :200
After swap, value of b :100
* &a indicates pointer to a ie. address of variable a and

* &b indicates pointer to b ie. address of variable b.


C++ function Call by reference
The call by reference method of passing
arguments to a function copies the reference of
an argument into the formal parameter. Inside
the function, the reference is used to access the
actual argument used in the call. This means
that changes made to the parameter affect the
passed argument.
#include <iostream>
using namespace std;
// function definition to swap the values.
void swap(int &x, int &y)
// function declaration
{
void swap(int &x, int &y); int temp;
temp = x; /* save the value at address x */
int main () { x = y; /* put y into x */
// local variable declaration: y = temp; /* put x into y */
int a = 100;
int b = 200; return;
}
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using When the above code is put
variable reference.*/ together in a file, compiled and
swap(a, b); executed, it produces the
following result −
Before swap, value of a :100
cout << "After swap, value of a :" << a << endl; Before swap, value of b :200
cout << "After swap, value of b :" << b << endl; After swap, value of a :200
return 0; After swap, value of b :100

}
Recursion
• A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Advantages and Disadvantages of
Recursion
Advantages of C++ Recursion
• It makes our code shorter and cleaner.
• Recursion is required in problems concerning data structures
and advanced algorithms, such as Graph and Tree Traversal.
Disadvantages of C++ Recursion
• It takes a lot of stack space compared to an iterative
program.
• It uses more processor time.
• It can be more difficult to debug compared to an equivalent
iterative program.
Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type, specify the name of the array followed
by square brackets and specify the number of elements it should store:

• string cars[4];

• We have now declared a variable that holds an array of four strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly braces:

• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

• To create an array of three integers, you could write:

• int myNum[3] = {10, 20, 30};


Access the Elements of an Array
• You access an array element by referring to the
index number.
• This statement accesses the value of the first
element in cars:
Example
• string cars[4] =
{"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
Loop Through an Array
• You can loop through the array elements with
the for loop.
The following example outputs all elements in
the cars array:
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++)
{
cout << cars[i] << "\n";
}
Omit Array Size
• You don't have to specify the size of the array.
But if you don't, it will only be as big as the
elements that are inserted into it:
string cars[] = {"Volvo", "BMW", "Ford"};
// size of array is always 3
• if you want extra space for future elements.
Then you have to overwrite the existing values:
string cars[] =
{"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
• If you specify the size however, the array will reserve the extra
space:
string cars[5] = {"Volvo", "BMW", "Ford"};
// size of array is 5, even though it's only three elements inside it

• Now you can add a fourth and fifth element without


overwriting the others:
cars[3] = {"Mazda"};
cars[4] = {"Tesla"};
Omit Elements on Declaration
• It is also possible to declare an array without specifying the elements on declaration,
and add them later:
int main()
{
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
for(int i = 0; i < 5; i++)
{
cout << cars[i] << "\n";
}
C++ Pointer to an Array
#include <iostream>
using namespace std;
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
Output :
p = balance;
Array values using pointer
// output each array element's value
cout << "Array values using pointer " << endl; *(p + 0) : 1000
*(p + 1) : 2
for ( int i = 0; i < 5; i++ ) {
cout << "*(p + " << i << ") : ";
*(p + 2) : 3.4
cout << *(p + i) << endl; *(p + 3) : 17
}
*(p + 4) : 50
cout << "Array values using balance as address " << endl;
Array values using balance as address
for ( int i = 0; i < 5; i++ ) { *(balance + 0) : 1000
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
*(balance + 1) : 2
} *(balance + 2) : 3.4
return 0;
*(balance + 3) : 17
} *(balance + 4) : 50
Passing Arrays to Functions
• Way-1
Formal parameters as a pointer as follows −
void myFunction(int *param)
{...
}
• Way-2
Formal parameters as a sized array as follows −
void myFunction(int param[10])
{...
}
• Way-3
Formal parameters as an unsized array as follows −
void myFunction(int param[])
{...
}
#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;

return 0;
}

double getAverage(int arr[], int size) {


int i, sum = 0;
double avg;

for (i = 0; i < size; ++i) {


sum += arr[i];
}
avg = double(sum) / size;

return avg;
} output : Average value is: 214.4

You might also like