Monday, September 20, 2010

Search For Number In Java

import java.util.*;
public class Example3
{
    public static void main (String [] args) 
    {
        int numbers[] = {1,2,3,4,5};
        int number = 0;
        int k, size;
        boolean found = false;
        k = 0;
        while (found == false && k<5) 
        {
            if (numbers[k] == number) {
            found=true;
            }
            else { 
            k ++;
            }
        
        }
        if(found)
            System.out.println("Found");
        else 
            System.out.println ("Not Found");
    }
}

The program will output found if the number is found, else not found. The program ends because it goes through the list one time, matching int number to the each number in the array.

1 comment: