I'm to find the smallest index of where a number is at in a for loop but it just won't give me the output I want,YET when I used the exact same code yesterday for the same problem it worked and the thing is the code is pretty much the exact same yet the one I did yesterday prints out the smallest index what I want it to do YET this one isn't doing the same even though the code is the same c++ can be frustraiting.
#include <iostream>
usingnamespace std;
int main()
{
int values[3];
int index = 0;
cout << "enter numbers" << endl;
for(int i = 0;i<3;i++){
cin >> values[i];
index = values[0];
if(values[index] > values[i]){
index = i;
}
}
cout << index;
}
Code yesterday which works fine
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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;
}
Ok I figured out the problem it's because the return is not before the last curly brace BUT how come I get a completely different output if I put the return index; in the for loops scope??
example VV
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int findSmallest(int ray[],int size){
int index;
index = 0;
for(int i = 0;i<size;i++){
if(ray[index] > ray[i]){
index = i;
}
return index;
}
}
VS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int findSmallest(int ray[],int size){
int index;
index = 0;
for(int i = 0;i<size;i++){
if(ray[index] > ray[i]){
index = i;
}
}
return index;
}
Yeah, I saw that. The approach I decided to take is I only need to know the index of the smallest and the rest falls into place. Each to their own I guess. :)
@kemort - The problem with your approach is you're always comparing ray[i] with smallest, but you're never updating smallest if you find a smaller entry.