elpretentio
elpretentio

Reputation: 15

identifying smallest index position of array in C++

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

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

  • The condition i > size is wrong. It should be i < size.
  • Don't forget to initialize temp. Write it as int temp = 0; because the initial value of n is the 0th element of the array.
  • You forget to use a block and the value of 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

Related Questions