Chapter 11

Home

Searching Through Arrays

Given an array and a target value, find whether it exists — and if so, where. The simplest approach checks every element in order: linear search.

Linear Search

Start at index 0 and compare each element with the target. If you find it, return the index or stop. If you reach the end, the target isn't there.

5 3 9 1 8 ... Searching for 3: check index 0 (no), index 1 (yes!)

Problem: Find first occurrence

Given N, an array, and a target X, print the first index where X appears, or -1 if not found.

Sample input:
5
4 7 1 9 3
9

Expected output:
3

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, target; cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i];
    cin >> target;

    int pos = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            pos = i;
            break;  // found — stop early
        }
    }
    cout << pos << "\n";
    return 0;
}

Rust

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i32> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = nums[0] as usize;
    let arr = &nums[1..=n];
    let target = nums[n + 1];

    let pos = arr.iter().position(|&x| x == target);
    match pos {
        Some(i) => println!("{}", i),
        None => println!("-1"),
    }
}

💡 break and early exit

Once you find the target, stop searching. break exits the loop immediately. For a large array, this can save significant time.

Count Occurrences

A variation: instead of stopping at the first match, count how many times the target appears.

C++

int count = 0;
for (int x : arr) {
    if (x == target) count++;
}
cout << count << "\n";

Rust

let count = arr.iter().filter(|&&x| x == target).count();
println!("{}", count);

Key Takeaways

Practice