Reputation: 15
i'm new here. i searched the existing questions for the answer to this problem, and it did help me progress but the code i have is still returning '0' instead of the actual position in the index of the smallest value in the array.
any help would be appreciated, thanks.
#include<iostream>
using namespace std;
int smallestIndex(int arr[], int size);
int main()
{
int arr[6] = {500, 29, 36, 4, 587, 624};
cout << "Index position for smallest element in array: "
<< smallestIndex(arr, 6) << endl;
return 0;
}
int smallestIndex(int arr[], int size)
{
int temp;
int n = arr[0];
for (int i = 0; i > size; i++)
{
if (arr[i] < n)
n = arr[i];
temp = i;
}
return temp;
}
Upvotes: 1
Views: 1006
Reputation: 75062
i > size
is wrong. It should be i < size
.temp
. Write it as int temp = 0;
because the initial value of n
is the 0th element of the array.temp
will be wrong.Fixed code:
int smallestIndex(int arr[], int size)
{
int temp = 0;
int n = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < n)
{
n = arr[i];
temp = i;
}
}
return temp;
}
Upvotes: 1