trying to find smallest index

hey guys I'm trying to find the smallest index of numbers I entered heres the code I used but the output surprises me as it's not close to what I want it to do instead it just prints out pretty much the first value of the first index,I actually want to print out the index which as the smallest value heres the code I used which failed,I'm not too sure how to break this algorithm down any idea guys?

thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int findSmallest(int ray[],int size){

    int smallest = ray[0];
    int index = 0;

    for(int i = 0;i < size;i++){

          ray[i];
          if(ray[index] > ray[i]){

            index = i;
          }


    }
       return smallest;
}
Line 8: This line does nothing. Why is it here?

Line 9: Check the comparison operator you're using. > is going to give you the larger of the two values. You want to execute line 11 if you find a smaller value. Hint: Use the < operator.

Line 16: You return smallest, but you only ever set smallest at line 3. Your problem statement says you want to return the index of the smallest value. Shouldn't you be returning index?



correct Anon I really need to get better at logic,it's not my strong suite,any ideas how I can actually improve on my programming logic?

and here is my new code that prints the smallest index,do you think theres anyway I can improve it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

int findSmallest(int ray[],int size){

    int smallest = ray[0];
    int index = 0;

    for(int i = 0;i < size;i++){

          if(ray[index] > ray[i]){

            index = i;
          }


    }
       return index;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
int findSmallest(int ray[],int size)
{   int smallest = ray[0];
    int index = 0;

    for(int i = 0;i < size;i++)
    {   if(ray[i] < smallest) 
        {   //  Found a smaller entry
            smallest = ray[i];
            index = i;
        }
    }
    return index;
}


Topic archived. No new replies allowed.