简体   繁体   中英

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;
           }
}

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

I guess you need sth like this:

boolean sequentialSearch(int x) {
    for(int i=0;i<n;i++) { //n comes from function length()
        if(list[i]==x){   // list comes from somewhere too
            System.out.println(i); // print i
            return true;
        }
    }
    return false;
}

If you need to print the last i possible start from the tail of array:

boolean sequentialSearch(int x) {
    for(int i=n-1;i>=0;i--) { //n comes from function length()
        if(list[i]==x){   // list comes from somewhere too
            System.out.println(i); // print i
            return true;
        }
    }
    return false;
}

Why u check i!=0, instead of iterate from i=1;

for(int i = 1; i < n; i++) 
 {
    if(list[i] == x) 
    { 
        return true;
    }
    return false;
 }

This much easier. :-)

Do you really want to print i and return a boolean? Since -1 is often used for not found , why not split this into two methods. Now you can search for whatever purpose you want, even if it's a system where System.out is unavailable as in a web application.

boolean sequentialSearch(int x) {
    for(int i = 0, n = list.length; i < n; i++) { 
        if(list[i] == x) {
            return i;
        }
    }
    return -1;
}

// Later
int index = sequentialSearch(y);
if (index != -1) {
    System.out.println(y + " found at index " + index);
} else {
    System.out.println(y + " not found");
}    

how to print the last value alone?

import java.util.Scanner;

public class Fibonacci {

    public static void main(String[] arguments) {
        int n1 = 0, n2 = 1, n3;

        @SuppressWarnings("resource")
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the value of n: ");
        int n = s.nextInt();
        for (int i = 0; i < n; ++i) {   
            n3 = n1 + n2;

            n1 = n2;
            n2 = n3;
        System.out.println(""+n3);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM