Linear search in a sorted array - Java

TinaXx picture TinaXx · Dec 24, 2015 · Viewed 8.9k times · Source

I want to make a program that searches linear in a sorted array and can output the different positions in which the searched item is found. At the moment my program only outputs the first position in which the search item is found, so here's an example from what what my program does right now:

Enter number of elements
5
Enter 5 integers
1
3
3
9
15
Enter value to find
3
3 is present at location 2.

Now the thing is that 3 is on location 2 and 3, and that's what i want to edit in the program but i don't know how to do it.

Here's the code of my program:

import java.util.Scanner;
 class LinearSearchArray1 {
    public static void main(String args[]){
        int c, n, search, array[];

        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements");
        n = in.nextInt(); 
        array = new int[n];

        System.out.println("Enter " + n + " integers");

        for (c = 0; c < n; c++)
        array[c] = in.nextInt();

        System.out.println("Enter value to find");
        search = in.nextInt();

        for (c = 0; c < n; c++)
        {
            if (array[c] == search)     /* Searching element is present */
            {
             System.out.println(search + " is present at location " + (c + 1) + ".");
            break;
        }
    }
    if (c == n)  /* Searching element is absent */
        System.out.println(search + " is not present in array.");
    }
}

Answer

Mohammed Aouf Zouag picture Mohammed Aouf Zouag · Dec 24, 2015
...
System.out.println("Enter value to find");
search = in.nextInt();

boolean exists = false;

for (c = 0; c < n; c++)
{
  if (array[c] == search)     /* Searching element is present */
  {
     System.out.println(search + " is present at location " + (c + 1) + ".");
     exists = true;
  }
}

if (!exists)  /* Searching element is absent */
  System.out.println(search + " is not present in array.");

You need to delete the break; statement. Otherwise, as soon as the first value is found, the loop is broken, & the next matches would never be reached.