Function and Recursion
Prepared By : Seif Tarek && Habiba Ghoname
Level 0
Agenda
Motivation
Functions
Scope variables
Function Overloading
Stack memory
Recursion
Stack overflow
Intro to Backtracking
Lamda Function
Motivation
Suppose you want to calculate
the sum of a factorial , b factorial
and minus c factorial You can
achieve this by using three loops
for
each variable and storing the
results in a variable named
“result” to display the final
outcome
We often find ourselves
rewriting the same factorial
code multiple times. Let’s
explore the power of functions
today, a tool that allows us to
write it once and use it many
times
Function
A functions is a block of code which only runs
when it is called The very first
function we knew
was main function
functions are used to perform certain
actions, and they are important for
reusing code:
define the code once , and use it
many times
That the main function is the only one that is
NOTE called automatically
When the program runs . It executes the main
function automatically
Why Do We Need Functions?
Functions reduce redundancy by avoiding repetitive
code, promoting reusability.
Code becomes modular and easier to read when divided into
functions.
Maintenance is simplified as changes are made in one place
for shared functionality.
Functions offer abstraction, enabling the use of library
functions without concern for internal details.
function make your code more organized:
since you give a block of code a name, and then when you
want to use you just call it's name instead of re-writing the
whole code again.
Function Declaration
Steps to define a function:
1. The first step is to determine what the
function should return int , float , char , You can pass data to functions, and also
string, or any other datatype receive data from functions (returned value)
2. If you don't want to return a value, set Any data can be passed to functions
the return type to void Any data type can be returned from function
3. Then name your function as you like
(preferred to use expressive names)
4. After the name put () If you want to send
parameters, put them inside the() print
sum(int x, int y)
You can define your own functions
Note : parameters must be defined by
you can define any number of functions as
type + name , and separated by commas
you need
5. Then between () write the body of the
Functions always contains parenthesis()
function
after
6. To return a value from a function, use
it's name, and it's body is written between ()
the
return keyword
Note : Any lines after the return keyword will
not be executed
Function Declaration
The syntax to declare a function is:
Return Type function Name Return Type: Specifies the data type
(parameter1,parameter2,...) of
{ the value returned by the function.
// function body Use "void" if the function doesn't
} return a value .
Function Name: The actual name of
the
Example Example function, combined with the
parameter
list, forms the function signature.
Parameters: Act as placeholders that
receive values when the function is
called. They are optional
Function Body: Contains a set of
statements defining the function's
operations.
Calling a Function
Formal parameter
While creating a C++ function, you give a
definition of what the function has to do. To int add( int a, int b ){
use a function, you will have to call or invoke
that function return a + b;
}
int main(){
Function
int result;
call
To call a function, you simply need to pass the result = add(5,3);
required parameters along with function name, cout<<result;
and if function returns a value, then you can store }
returned value.
Actual parameter
Function Prototype
A function prototype provides information, such as the
number and type of parameters and the type of return
values, to explain the function interface to the compiler.
The function prototype feature in allows
NOTE us to call the function before it has been
declared
Scope variables
The scope is defined as the extent of the program code within
which the variable can be accessed or declared or worked with.
There are mainly two types of variable scopes:
Local Variables
Global Variables
Output: 2
Scope variables
Anything between ‘{‘ and ‘}’ is said to inside a block. They are available through out the life time of
Local variables do not exist outside the block in a program.
which they are declared, i.e. They are declared at the top of the program
they can not be accessed or used outside that block. outside all of the functions or blocks.
Declaring local variables: Local variables are Declaring global variables: are usually
declared inside a block. declared
outside of all of the functions and blocks, at
the top of the program. They can be accessed
from any portion of the program.
Local Variables defined within a function or
block are said to be local to those functions.
Global Variables As the name suggests,
Output: Error: age was
Global Variables can be accessed from
not declared in this scope
any part of the program.
Output : 5 10
Function call methods
There are two most popular ways to pass parameters:
Pass by Reference: Both actual and formal parameters refer to
the same locations, so any changes made inside the function
are reflected in the actual parameters of the caller.
Output: 10 5
Pass by Value: In this parameter passing method, values of
actual parameters are copied to the function’s formal
parameters. The actual and formal parameters are stored in
different memory locations so any changes made in the
functions are not reflected in the actual parameters of the
caller.
Output: 5 10
Function
Now, we can solve the problem we discussed in
motivation, where we need to calculate factorial a!
+ factorial b! - factorial c!, using functions to create
an implementation that is better than the other
implementation we did in the previous code.
Output :124
Problem A
Problem C
Problem B
Passing arrays as parameters
The whole array cannot be passed as an argument to a Pointer to arr Length of
function. However, you can pass a pointer to an array arr
without an index by specifying the array’s name.
void printArray (int a[], int size)
{ The length of arr is
for(int i=0;i<size;i++) passed. It is
Arrays are always passed to the function as pointers { cout<<a[i]<<" "; compulsory to pass
pointing to the first element of the array. } size as is just a
int main(){ pointer
Pointer a int arr[] = {1, 2, 3, 4, 5);
Syntax takes the base int size = sizeof(arr) / sizeof(arr[0]);
Return_type function name address of printArray ( arr , size ); }
( array_type array_name[size],...); array arr
ــــــ ـــــ
Problem D
Problem E
Function Overloading
one of the following conditions for Function
overloading:
Parameters should have a different type
If multiple functions having same name but
Parameters should have a different number
parameters of the functions should be
Parameters should have a different sequence
different is known as Function Overloading.
of parameters.
have a different type have a different number have a different sequence of parameters.
Stack memory
When a function is called, its memory is allocated on a
stack. Stacks in computing architectures are the
regions of memory where data is added or removed in
a last-in-first-out (LIFO) process.
When a function executes, it adds its state data to the
top of the stack. When the function exits, this data is
removed from the stack.
Stack memory
Stack Stack Stack Stack Stack Stack
Sq()
x
sos() sos()
sos()
x,y,z x,y,z x,y,z
main() main() main() main()
main()
a,b a,b a,b a,b
a,b
Step 1 Step 2 Step 3 Step 4 Step 5 Step 6
Recursion
Syntax
Recursion is a technique in which a function calls itself
repeatedly until a given condition is satisfied. In other
words, recursion is the process of solving a problem by
breaking it down into smaller, simpler sub-problems.
to solve a problem recursively, we need 3 things: base case :
when to stop ?
transition : what the moves between states should look like ?
initial state : from where to begin ?
Recursion
To understand how recursion works, we will refer
to an example of how to sum from 1 to n and trace
the flow of the program. Recursion Diagram of nSum(5) Function
Recursion
Step 1 Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Stack overflow
Stack overflow is one of the most common errors associated
with the recursion which occurs when a function calls itself too
many times. As we know that each recursive call requires
separate space in the limited stack memory. When there is a
large number of recursive calls or recursion goes on infinite
times, this stack memory may get exhausted and may not be
able to store more data leading to programs’ termination.
Tail recursion
Tail Recursion: If a recursive function calling itself
and that recursive call is the last statement in the
function then it’s known as Tail Recursion. After that
call the recursive function performs nothing. The
function has to process or perform any operation at
the time of calling and it does nothing at returning
time
The space complexity of the provided
code is O(n), where "n" is the value Output : 3 2 1
passed to the function fun. This is
NOTE due to the recursive nature of the
function, and each recursive call adds
a new frame to the call stack until the
base case is reached.
Head Recursion
Head Recursion: If a recursive function
calling itself and that recursive call is
the first statement in the function then
it’s known as Head Recursion. There’s
no statement, no operation before the
call. The function doesn’t have to
process or perform any operation at the
time of calling and all operations are
done at returning time.
Output : 3 2 1
Tree recursion
Tree recursion is a programming concept where a function calls
itself, creating a recursive structure resembling a tree. Each
recursive call spawns additional calls, forming a branching
pattern similar to the nodes and branches of a tree.
Fibonacci series is a sequence of Integers that starts
with 0 followed by 1, in this sequence the first two
terms i.e. 0 and 1 are fixed, and we get the
successive terms by summing up their previous last
two terms
The Fibonacci function has exponential time
complexity, denoted as O(2^n), because of
NOTE
repeated and redundant computations in
recursive calls, leading to a rapid increase in
function calls and computations as the input
parameter "n" representing the sequence position
grows.
Problem F Problem H
Problem G
Intro to Backtracking
Backtracking can be defined as a general algorithmic
technique that considers searching every possible
combination in order to solve a computational problem.
For example, consider the SudoKo solving Problem, we try
filling digits one by one. Whenever we find that current digit
cannot lead to a solution, we remove it (backtrack) and try
next digit. This is better than naive approach (generating all
possible combinations of digits and then trying every
combination one by one) as it drops a set of permutations
whenever it backtracks.
lambda function
C++ Lambda expression allows us to
define anonymous function objects
(functors) which can either be used
inline or passed as an argument.
lambda function