array and recursive functios examples

Hey guys ..
Can anyone give me an examples for recursive functions and arrays, a simple examples of an array, like sort one or do a mathematic operations on an array (or more than one) and add the resut in a new array. I need it for an exam tomorrow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iterator>
#include <iostream>

int sum(int* a, unsigned size, int acc = 0)
{
   if ( size == 0 )
      return acc ;
   else
      return sum(a+1, size-1, acc + *a);
}

int main()
{
   int array[] = { 1, 2, 3, 4, 5, 6 } ;
   unsigned array_size = std::end(array) - std::begin(array) ;

   std::cout << sum(array, array_size) << " is the sum of elements in array.\n" ;
}


http://ideone.com/C08jQ0
Nice one, thnx.
But I need more examples if possible, not necessarily that the array and the recursive functions to be in the same code, bu nice what you give.
If anyone else, or you, could give me another examples please.
Computing N! or the Fibonacci sequence are both typical examples of recursive functions (even though both can be computed without recursive more efficiently). Try looking those up. Also, when starting out, it's a good idea always to code recursive functions like this:
1
2
3
4
5
if (this is the base case) {
    return the base result;
} else {
    do the recursive processing
}


This will help you think of the two cases separately and will also help to avoid infinite recursion, which can be hard to debug.

For arrays, you might try finding the dot-product of two arrays, or finding smallest or largest item in an array.
thanx for help dhayen
Topic archived. No new replies allowed.