# Return Smallest Index

Printable View

• 02-25-2009, 02:31 AM
Gamerpro
Return Smallest Index (Solved)!
Up front, I want to thank anyone for helping me with this task.

I was recently given this task:
Create a method called findElementIndex, which takes an integer and an integer array as input parameters, and returns the smallest index where that value appears. If the value is not in the array, the method should return -1.

Example:
value: 3 theArray:{10, 3, 6, 3, 8, 10} ==> 1
value:10 theArray:{11, 3, 6, 7, 9, 60} ==> -1

So far, I have this:

int index = 0;
for(int i = 0; i < theArray.length; i++){
if (theArray[i] == value) {
index = i;
}
else if (theArray[i] != value){
index = -1;
}
}
return index;
• 02-25-2009, 03:06 AM
emceenugget
two problems with your algorithm:

1. it iterates through the whole loop. even if you find the first incidence of the input 'value', it will keep going.

2. it iterates through the WHOLE loop, setting a new value for 'index' each time around, meaning your final value will either be the last index or -1.
• 02-25-2009, 03:14 AM
CJSLMAN
OK.. you seem to be on the correct track... some corrections and minor tweaks.
• No need to for the else... let the for loop run it's course.
• No need for index variable ...

Code:

```for(int i = 0; i < theArray.length; i++){ if (theArray[i] == value) { [COLOR="Blue"][B]return i; [/B][/COLOR] } } [COLOR="Blue"][B]return = -1; //value not found [/B][/COLOR][B][/B]```
Luck,
CJSL
• 02-25-2009, 03:27 AM
Gamerpro
Oh.....
O.K. Thanks a lot, I see what I was doing wrong; I was trying the code you gave me and I kept on getting errors because I didn't notice the return = -1 in your above post, it was supposed to be return -1, silly me! I appreciate the help from both of you!
• 02-25-2009, 03:31 AM
CJSLMAN
welcome
sure, no problem...

Luck,
CJSL