Linear Search & Element Frequency Program in Java (ICSE)

⚡ Direct Answer & Key Takeaway

Linear Search inspects an array sequentially from index `0` to `n-1` and works on both sorted and unsorted arrays. Unlike a first-match search that exits early with `break`, finding element frequency lets the `for` loop traverse every slot, incrementing `count++` whenever `arr[i] == key`. Afterward, `count > 0` confirms presence and total occurrences, whereas `count == 0` reports the target key is absent.

1. First-Match Search vs Full-Scan Frequency Counting

Beginning programmers often copy a standard Linear Search containing `break;` into a frequency question and wonder why Java always outputs `1`. When a question only asks whether a number exists or asks for its first index, `break;` is ideal because it skips redundant checks after finding `key`. However, when ICSE asks for 'frequency of a number', 'all positions where key appears', or 'count of students scoring 100', you must omit `break;` so `i` visits every element through `n - 1`. Initializing `int count = 0;` and `int firstPos = -1;` lets one single pass report both the first location (`if (firstPos == -1) firstPos = i;`) and the exact total frequency.

  • Linear Search needs zero pre-sorting—it works immediately on raw user-entered arrays.
  • Never write an `else { System.out.println("Not found"); }` inside the `for` loop, or it prints on every mismatching element.
  • Check `if (count > 0)` once after the loop ends to print either the frequency or a single 'Not found' message.
  • For `String[]` Linear Search, replace `arr[i] == key` with `arr[i].equalsIgnoreCase(key)`.

2. Dry Run on {14, 7, 29, 7, 42, 7, 19} Searching for 7

Trace `arr = {14, 7, 29, 7, 42, 7, 19}` (`n = 7`) when searching for `key = 7` with `count = 0` and `firstPos = -1`. At `i = 0`, `14 != 7`, so counters stay `0` and `-1`. At `i = 1`, `arr[1] == 7` matches: `count` becomes `1`, and because `firstPos == -1`, `firstPos` locks at `1`. At `i = 2`, `29 != 7`. At `i = 3`, `arr[3] == 7` increments `count` to `2` while `firstPos` stays `1`. At `i = 4`, `42 != 7`. At `i = 5`, `arr[5] == 7` makes `count = 3`. Finally `i = 6` checks `19 != 7`. After the loop ends, Java prints `firstPos = 1` and `count = 3`.

  • Best case takes `1` comparison (`key` at index `0` with `break`); frequency counting always takes `n` comparisons.
  • `if (firstPos == -1)` ensures only the earliest index is captured while `count` keeps accumulating.
  • Collecting all positions can also be printed inline inside the `if` block as `System.out.print(i + " ");`.

3. Board Exam Patterns: Parallel Arrays & Frequency of Every Element

ICSE Class 9 and 10 papers feature two major Linear Search variations beyond finding a single number. First, parallel-array lookup stores two linked lists—such as `String[] countries` and `String[] capitals`, or `int[] rollNo` and `double[] marks`—where matching `key` at index `i` prints the paired record `capitals[i]` or `marks[i]`. Second, finding the frequency of every unique element in an array uses a nested loop or a `boolean[] visited` array so previously counted duplicates are skipped instead of printed twice. Mastering single-key frequency first makes both board variations intuitive and error-free under exam time pressure.

  • For parallel arrays (like State and Capital), always test `states[i].equalsIgnoreCase(key)` and output `capitals[i]`.
  • When counting multiple conditions (e.g., frequency of even vs odd or positive vs negative), use separate counters inside one loop.
  • In Section A, Linear Search is often contrasted with Binary Search in a 2-mark differences table.

4. LinearSearchFrequency.java (Presence, Index & Frequency)

import java.util.*;

public class LinearSearchFrequency {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("Enter element to search: ");
        int key = sc.nextInt();

        int count = 0;
        int firstPos = -1;

        for (int i = 0; i < n; i++) {
            if (arr[i] == key) {
                count++;
                if (firstPos == -1) {
                    firstPos = i;
                }
            }
        }

        if (count > 0) {
            System.out.println("Element found! First index: " + firstPos);
            System.out.println("Frequency of " + key + ": " + count);
        } else {
            System.out.println("Element " + key + " not found in the array.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter number of elements: 7
Enter 7 integers:
14 7 29 7 42 7 19
Enter element to search: 7
Element found! First index: 1
Frequency of 7: 3

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintStores total size of the array entered by user (Sample: 7)
arr[]int[]Stores unsorted integer elements to scan sequentially (Sample: {14, 7, 29, 7, 42, 7, 19})
keyintTarget element whose presence and frequency are checked (Sample: 7)
iintLoop index traversing sequentially from 0 to n - 1 (Sample: 0 to 6)
countintFrequency counter incremented each time arr[i] == key (Sample: 3)
firstPosintStores index of first occurrence or -1 if absent (Sample: 1)
🎯 1-on-1 Live Mentorship & Free Study Kit

Build Rock-Solid Array Search Skills for ICSE Computer

Work 1-on-1 with a BlueJ Java tutor on parallel array lookups, element frequency counters, and clean VDT writing to boost your Class 9 & 10 Computer Applications score.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Putting `else { System.out.println("Not Found"); }` inside the `for` loop, which prints 'Not Found' multiple times before the scan even finishes.
  • Avoid Mistake: Adding `break;` inside the match block when counting frequency, which stops after the first match and always reports frequency `1`.
  • Avoid Mistake: Using `==` instead of `.equals()` or `.equalsIgnoreCase()` when adapting Linear Search to parallel `String[]` arrays like names or capitals.
  • Examiner / Mentor Tip: In a 2-mark Section A comparison between Linear and Binary Search, highlight two points: Linear Search works on unsorted arrays, whereas Binary Search requires sorted arrays and is faster on large lists.
  • Examiner / Mentor Tip: Read the question carefully for 'index' (0-based `i`) versus 'position' (1-based `i + 1`)—CISCE often asks for 'position' in human-readable output.
  • Examiner / Mentor Tip: Always reset `count = 0` before scanning if your program searches multiple keys inside an outer loop.

7. Interactive Concept Check Quiz

Question: If a student mistakenly puts a break; statement inside the if (arr[i] == key) block while scanning {5, 8, 5, 12, 5} for key = 5, what will the program print as the frequency?

8. Frequently Asked Questions

When should I prefer Linear Search over Binary Search in ICSE Java?
Choose Linear Search whenever the input array is unsorted, small, or when you need to count total occurrences of a duplicate key. Sorting an unsorted array solely to run one Binary Search takes more operations than running a single Linear Search directly. Use Binary Search only when the array is already sorted or queried repeatedly.
How do I print every index where an element appears instead of only the first index?
Inside the if (arr[i] == key) block, print i (or i + 1 for 1-based position) immediately along with incrementing count++. You can also print a heading like "Found at indices: " only when count == 1, or check if (count == 0) after the loop finishes to display the not-found message cleanly.
How can I find the frequency of every distinct number in an ICSE array?
Use a boolean[] visited = new boolean[n]; array alongside nested loops. For each index i where !visited[i], start count = 1 and scan j from i + 1 to n - 1; whenever arr[j] == arr[i], increment count++ and mark visited[j] = true so duplicate values are counted once and never printed again.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class