Chapter 11
HomeGiven an array and a target value, find whether it exists — and if so, where. The simplest approach checks every element in order: 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.
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
#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;
}
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.
A variation: instead of stopping at the first match, count how many times the target appears.
int count = 0;
for (int x : arr) {
if (x == target) count++;
}
cout << count << "\n";
let count = arr.iter().filter(|&&x| x == target).count();
println!("{}", count);
break to stop early once found.
.position() (Rust) returns Option<usize> — the index or None.