Home > Software design >  why is my code not finding the index in my array?
why is my code not finding the index in my array?

Time:12-13

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.

#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];

    for (i = 0; i < size; i  )
    {
        
        if (min > array[i])
        {
            min = array[i];
            
        }
        index  ;
    }
    cout << "The smallest number is " << min << " and is found at index " << index;
    return 0;
}

CodePudding user response:

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';

CodePudding user response:

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
            
        }
        index  ;
    }
    cout << "The smallest number is " << min << " and is found at index " << index;
    return 0;
}
  • Related