Recursion exercises

  1. Write a recursive method that computes the sum of all numbers from 1 to n, where n is given as parameter.
    //return the sum 1+ 2+ 3+ ...+ n
    int sum(int n)
    

  2. Write a recursive method findMin that takes as parameter an array and finds and returns the minimum element in the array.
    //return the minimum element in a[]
    int findMin(int a[], ...)
    

  3. Write a recursive method findSum that takes as parameter an array and computes and returns the sum of all elements in the array.
    //return the sum of all elements in a[]
    int findSum(int a[], ...)
    

  4. Write a recursive method that takes as parameter an array and determines whether the array is a palindrome.
    //returns 1 if a[] is a palindrome, 0 otherwise
    int isPalindrome(char a[], ...)
    

  5. Write a recursive method that searches for a target in a sorted array using binay search, where the array and the target are given as parameters.
    //if target is not in array a it returns -1
    //if target is in the array a it returns the position where it occurs
    int binarySearch(int a[], int target, ...)
    
In all these example you will need to think what arguments to add to the method that you write, in order to be able to call that method, recursively, on a "sub-problem". You are the one designing your method, so you can design it in whatever way is convenient to you.

For example, look at findMin. One way to find the minimum element of an array of n elements, recursively, is as follows:

min[a1....an] = the smaller of { a1, min[a2...an]} 
Thus, to find the minimum element in an array of n elements, we need to call the method on an array of n-1 elements, that is elements 2 through n of a. So, we need to design the method findMin so that it takes anotehr argument, which specifies what part of the array it is currently looking at.