Search This Blog

Recursion Smallest element of array C++

Write a recursive function that finds and returns the minimum or smallest elemnt in an array, where the array and its size are given as parameters.

Solution:

#include <iostream>
using namespace std;

int smallest_element(int [], int size);

int main()
{
int array[5] = {9,-8,1,8,-7};
cout << "Smallest element of array is " << smallest_element(array,5) << endl;
return 0;
}

//Function
int smallest_element(int array[], int counter)
{
int smallest;
if (counter == 1)
return array[0];
else
{
smallest = smallest_element(array+1,counter-1);
if (smallest < array[0])
return smallest;
else
return array[0];
}
}
"Don't let anyone ever make you feel like you don't deserve what you want."