Solution Exercise Recursion
Solution Exercise Recursion
Exercise 1
• Find the number of calls done for the factorial function with n=10.
Exercise 2
• Write an iterative and recursive function for calculating the length of a string of
characters.
Exercise 3
• Write a recursive function that returns the sum of squares for the first n
elements of an array with positive integers.
Exercise 4
• Write an iterative function that converts from decimal to binary.
Exercise 5
• Write a recursive function that finds the smallest element in an array
1
Exercises
Exercise 6
• Write an iterative and recursive function for searching the element
index of an element in an array of names sorted in alphabetic order
Exercise 7
• Write a recursive boolean function that determines if a string in
palindrom or not. E.g., the word LAYAL is palindrom
Exercise 8
• Write a recursive function that calculates the pgcd of 2 numbers
using the Euclidian method
• pgcd(a,b)=a if a=b
• pgcd(a,b)= pgcd(a-b,b) if a>b
• pgcd(a,b)= pgcd(a,b-a) if b>a 2
Exercises
Exercise 9
• Write a recursive function that evaluates a polynom having the
form a0+a1x+a2x2+…+anxn, where x and n are passed as integer
arguments, and the n+1 coefficients ai are passed to the function as
an array
Exercise 10
• Write a recursive function that determines the combination number
of k objects between n, using the Pascal triangle
• C(n,k)=1 if k=0
• C(n,k)=1 if k=n
• C(n,k)= C(n-1,k-1)+ C(n-1,k) if 0<k<n
• C(n,k)=0 if k<0 3
//Recursion ex1 : number of calls for factorial of 10
➔ 10 calls
//Recursion ex2 : length of a string
}
//ex4: iterative function that converts from decimal to binary
long dectobin(int n)
{
long bin = 0, i=1;
while(n!=0)
{
bin = bin + n%2 * i;
i=i*10;
n=n/2;
//ex5: find the smallest element in an array
}
return bin; int smallest (int *A, int n)
} {
if(n<=1)
return A[0];
// Iterative binary search function to find the index of a target in a sorted array
// Recursive binary search function to find the index of a target in a sorted array
int main() {
// Iterative search
int indexIterative = binarySearchIterative(A, n, target);
if (indexIterative != -1)
cout << "Found " << target << " at index (iterative): " << indexIterative << endl;
else
cout << target << " not found (iterative)." << endl;
// Recursive search
int indexRecursive = binarySearchRecursive(A, 0, n - 1, target);
if (indexRecursive != -1)
cout << "Found " << target << " at index (recursive): " << indexRecursive << endl;
else
cout << target << " not found (recursive)." << endl;
return 0;
}
//ex7: recursive boolean function that determines
//if a string in palindrom or not
int main()
{
int A[4] = {1, 2, 3, 4};
int x = 2;
int n = 3;
cout<<polynome (x, n, A, 0);
return 0;
}
//ex9: recursive function that determines the combination number of k objects between n, using the Pascal triangle