joe smoe joe smoe - 1 month ago 9
Java Question

Outputting value of a For-Loop on last iteration only


I am trying to output the value of
i
for the loop
index(i)
, but only on the last iteration.

I either get an error or it outputs all values of
i
. Here is what I have so far:


boolean sequentialSearch(int x) {

for(int i = 0; i < n; i++) //n comes from function length()

if(n != 0) {

if(list[i] == x) {

return true;
}

return false;
}
}

Answer

Try:

for(int i = 0; i < n; ++i) {
    if(list[i] == x) { // an array is 0-indexed
        System.out.println("Found at index: " + i);
        return true;   // return true if found
    }
}
System.out.println("Not found!");
return false;      // here, x has never been found, so return false
Comments