Write a c++ function, smallestIndex, that takes as parameters an int array and its size and returns the index of the first occurrence of the smallest element in the array. Also, write a program to test your function.
#include<iostream>
usingnamespace std;
int smallestIndex(int list[], int listSize);
int main()
{
int alpha[20];
cout << "The index of the first occurrence of the smallest element in the array is " << smallestIndex(alpha,20) << endl;
return 0;
}
int smallestIndex(int list[], int listSize)
{
int counter;
int minIndex = 0; //Assuming first element is the smallest
for (counter = 1; counter < listSize; counter++)
if (list[minIndex] > list[counter])
minIndex = counter;
return minIndex;
}
This does work, however I am getting 0 returned from the function. But somehow I doubt this is what I should get and I think is something else I must do, unless this is of course a stupid exercise.
You should adapt your boundary depending on the number of elements you enter. In other words don't check always for 20 elements but for any given value N <=20. Of course in case where alpha = {2,4,5,9,11,15} index 6 is unacceptable (it should be 0-5).