Programming: Array manipulation using recursion

Fernando Arana Salas
4 min readJan 30, 2022

The idea is to manipulate an array by applying the concept of recursion.

We are going to print, add, multiply and do a sequential search on the elements of an array.

Let’s first recall some principles of arrays.

An array is a collection of elements or variables that are stored successively in a memory space.

In this example we declare an array with 6 slots to store int integers.

Once we have an array declared, we can play around with it

First, we’re going to need the length of our array. From the beginning we know that it is 6 spaces; however, if we don’t know it (as would be the case with an array of characters entered by the user), we calculate it like this:

In this line of code we use pointers and references (* &). To learn about this programming concept click here.

Exercise 1: Print an array/vector using a recursive function.

Here, the base case is: when the index reaches the last position of the array.

The recursive case is: when call the function again within the function, but with an updated parameter, in this case the index plus +1.

Result: 97 75 65 100 0 -10

Exercise 2: Print an array/vector in reverse using a recursive function.

To print an array in reverse, we must start at the last element of the array, that is array[len — 1] so, the recursive case must decrease the parameter len .

The base case is: when the parameter len has gotten all the way to the initial index position — which is 0 — .

Result: -10 0 100 65 75 97

Exercise 3: Sum all the elements of a vector with recursion.

Here, the base case is: when the index reaches the last position of the array.

The recursive case is: when call the function again within the function, but with an updated parameter, in this case the index plus +1 AND the sum of the current element.

Result: 327

Exercise 4: Calculate the product of all the elements of an array with recursion.

Here, we must check for three cases.

  1. The base case happens when the index reaches the last position of the array.
  2. In case of an error: which checks if there’s a 0 within the elements of the array.

3. The recursive case happens when call the function again within the function, but with an updated parameter, in this case the index plus +1 AND the product of the current element.

Result: "The array contains a zero, which makes the product result zero. Error Code: 47287500"

Exercise 5: Implement a recursive sequential search on an array

Again, we have three cases:

  1. The base case happens when the index position is bigger than the length of the array, which means that the element wasn’t found.
  2. The success case which happens if the element is found.
  3. The recursive case, which calls the function with an updated parameter.
Result: 4

Complete code

--

--