joe smoe joe smoe - 1 year ago 67
Java Question

Outputting value of a For-Loop on last iteration only

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

I either get an error or it outputs all values of
. 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 Source


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download