NU-Lec 3 - Functions Overloading and Recursion
NU-Lec 3 - Functions Overloading and Recursion
Lecture No. 3
Functions Overloading and
Recursion
2
Pointer to Pointer
• The declaration of a pointer-to-pointer looks like
– int **ipp;
• The two asterisks indicate that two levels of pointers are
involved
– e.g.
int i = 5, j = 6; k = 7;
int *ip1 = &i, *ip2 = &j;
ipp = &ip1;
3
Dynamic 2D arrays
4
Dynamic 2D arrays
• At the first level, it points to a block of pointers,
one for each row. That first-level pointer is the
first one we allocate; it has nrows elements, with
each element big enough to hold a pointer-to-int,
or int *.
5
Dynamic 2D arrays
What is function overloading?
• Function overloading is the important characteristic of
OOP.
Two arguments
draw();
draw(‘=’);
draw(‘*’ , 30);
}
Recursion
• An extremely powerful problem-solving technique.
Formula
• n = n+(n-1)+(n-2)+(n-3)………3+2+1
Iterative method
int sum(int n)
{
if (n == 0)
{
return 0;
}
int value = 1;
for (int i = n; i > 1; i--)
{
value = value + i;
}
return value;
}
Example- Sum(Cont…..)
Base Case (The case where recursive call stops)
• In sum, the base case is sum(0)=0
Recursive Case
• sum(n) = n + sum(n-1)
Recursive Method
int sum(int n)
{
if (n == 0)
{
return 0;
}
else
{
return n + sum(n - 1);
}
}
Example- Factorial
Mathematical Examples
• 4! = 4 * 3 * 2 * 1 = 24
• 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
Formula
• n! = n*(n-1)*(n-2)*(n-3)………3*2*1
Iterative method
int factorial(int n)
{
if (n <= 1)
{
return 1;
}
int value = 1;
for (int i = n; i > 1; i--)
{
value = value * i;
}
return value;
}
Example- Factorial(Cont…..)
Base Case (The case where recursive call stops)
• In factorial, the base case is factorial(0)=1
Recursive Case
• fact(n) = n * fact(n-1)
Recursive Method
int factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * factorial (n - 1);
}
}
15
Example- Factorial(Cont…..)
Example- Print Reverse
Mathematical Examples
• 4=4 3 2 1
• 7=7 6 5 4 3 2 1
Formula
• ?
Base case
• ?
Recursive case
• ?
Recursive method
• ?
Example- Fibonacci sequence
Mathematical Examples
• The first ten terms in the sequence are:
1,1,2,3,5,8,13,21,34,55
To be done by students..….