Let me show you the logical step through using just 3 numbers - 1, 3, 2.

The offending code is the following:

int min = a[0];
int max = a[0];
...
if (min > a[k])
{
min = a[k];
min_index=k;
}
else
{
max = a[k];
max_index=k;
}

So, for k = 0 to 2:

k = 0: min = 1, max = 1, a[k] = 1

min == a[k] - run code in "else"

Result: max = 1, max_index = 0

k = 1: min = 1, max = 1, a[k] = 3

min < a[k] - run code in "else"

Result: max = 3, max_index = 1

k = 2: min = 1, max = 3, a[k] = 2

min < a[k] - run code in "else"

Result: max = 2, max_index = 2

There are a few points (the first is a choice):

1a: the for loop should start from 1, not 0 - or

b: "min" initialized to

`std::numeric_limits<int>::max()`

(

`#include <limits>`

) and "max" initialized to 0

2: the

`else`

should be replaced by a separate

`if`

statement that checks against max - the "k = 2" proves why (max would just get overwritten)

If we pick the second option, the code would result as follows:

#include <limits>
void min_max(int a[], int length)
{
int min = std::numeric_limits<int>::max();
int max = 0;
int min_index=0, max_index=0;
for (int k = 0; k < length; k++)
{
if (min > a[k])
{
min = a[k];
min_index=k;
}
if (max < a[k])
{
max = a[k];
max_index=k;
}
}
cout << '\n';
cout<<"Maximum number is: "<< max <<endl;
cout << "Max_Index: " << max_index << endl;
cout<<"Minimum number is: "<< min <<endl;
cout << "Min_Index: " << min_index << endl;
}

I haven't looked at the rest of the code, so if there are problems there, you can try and work them out!