'why is my code not finding the index in my array?
I've put my code below. Basically, I find the lowest number of an element in the array, and I also want it to find the index of the lowest element. It finds the index with a fairly low amount of elements, but for some reason it sometimes just seems to return random numbers for the index, and I have no idea why.
Solution 1:[1]
You are increasing the variable index in each iteration of the for loop
index++;
And the variable min is redundant.
The for loop can look the following way
for (i = 1; i < size; i++)
{
if ( array[i] < array[index] )
{
index = i;
}
}
cout << "The smallest number is " << array[index] << " and is found at index " << index;
Pay attention to that there is standard algorithm std::min_element() that performs the same task.
For example
#include <iterator>
#include <algorithm>
//...
auto min = std::min_element( array, array + size );
std::cout << "The smallest number is " << *min << " and is found at index " << std::distance( array, min ) << '\n';
Solution 2:[2]
you need just add an index var on out of your loop and set it to zero . then evry time your max item has changed , your index changes too.
#include<iostream>
using namespace std;
int main()
{
int min;
int array[100];
int size;
int i;
int index = 0;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> array[i];
}
min = array[0];
index =0
for (i = 0; i < size; i++)
{
if (min > array[i])
{
min = array[i];
index =i
}
i++;
}
cout << "The smallest number is " << min << " and is found at index " << index;
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Remy Lebeau |
| Solution 2 |
