1

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;

}

1 Answer 1

1
  • 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;

}
Sign up to request clarification or add additional context in comments.

4 Comments

oh wow, ok thanks very much. was racking my brain and it was really mainly just the wrong relational symbol. all very helpful, thanks.
also i'm not sure if i should post this as a new thread.. but the second part of this problem is to write a program that tests the function. so would that be something that generates random numbers for an array? the professor was kind of purposefully vague, just trying to explore all types of input from others.
That problem makes sense. Write some.
Random test cases are sometimes used, but I don't think it is suitable here. In testing, you have to know what is the expected answer for each test case. Here are example of test cases: the first element is the smallest, the last element is the smallest, an element in middle is the smallest, all elements have the same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.