Problem 8 • Arrays
Author: Er. Manoj Kumar • Computer Science Fundamentals
Linear Search in an Array of N Elements with Early Exit
📋
Problem Statement
Given an array Arr of N integers and a target Key, perform a sequential scan from index 0 to N-1. If Arr[i] == Key, record the index, set Found = 1, and immediately break early to eliminate redundant comparisons.
📊
Variable Dictionary / Table
| Variable Name | Data Type | Role & Purpose |
|---|---|---|
| N | Integer | Total number of elements in the array |
| Arr[0..N-1] | Array of Integers | Collection of sequential data |
| Key | Integer | Target value being searched |
| Found | Integer (Flag 0 or 1) | 0 = not found, 1 = found |
| i | Integer | Loop iteration index |
📝
Step-by-Step Formal Algorithm
Step 1: Start.
Step 2: Read N.
Step 3: Read array elements Arr[0], Arr[1], ..., Arr[N-1].
Step 4: Read target Key.
Step 5: Set Found = 0, i = 0.
Step 6: While (i < N):
If (Arr[i] == Key):
Print 'Key found at position i'.
Found = 1.
Break loop (Go to Step 7).
Else:
i = i + 1.
Step 7: If (Found == 0):
Print 'Key not present in array'.
Step 8: Stop.
🔀
Flowchart (Interactive Graphical Diagram)
flowchart TD
Start([Start]) --> InArr[/"Read N and Array elements Arr[0..N-1]"/]
InArr --> InKey[/"Read target Key to search"/]
InKey --> Init["Initialize index i = 0, Found = 0"]
Init --> LoopCond{"Is i < N ?"}
LoopCond -- Yes --> MatchCond{"Does Arr[i] == Key ?"}
MatchCond -- Yes --> SetFound["Set Found = 1"]
SetFound --> OutFound[/"Print 'Key found at index i'"/]
OutFound --> EarlyExit[/"⚡ Early Exit Break Loop"/]
EarlyExit --> Stop([Stop])
MatchCond -- No --> Inc["i = i + 1"]
Inc --> LoopCond
LoopCond -- No --> ChkFound{"Is Found == 0 ?"}
ChkFound -- Yes --> OutNotFound[/"Print 'Key not present in array'"/]
OutNotFound --> Stop
ChkFound -- No --> Stop
🖥️
Flowchart (ANSI Terminal ASCII Chart)
+-----------------+
| [ START ] |
+-----------------+
|
v
+-----------------+
| Read N & Array |
| Read Key |
+-----------------+
|
v
+-----------------+
| Found=0, i=0 |
+-----------------+
|
v
/ \
/ i < N ? \ ---NO---> / \
\ / / Found==0?\ ---YES--> [Print Not Found] --> [STOP]
| YES \ /
v | NO
/ \ v
/Arr[i]==Key?\ [STOP]
\ /
YES/ \NO
v v
+--------------+ +-----------+
| Set Found=1 | | i = i + 1 |
| Print pos i | +-----------+
+--------------+ |
| +------> (Loop to i < N?)
v
[ EARLY EXIT ] --> [ STOP ]
🧪
Dry-Run Execution Trace Table
| Execution Step / Case | Variables State 1 | Variables State 2 | Condition Evaluation | Output / Result |
|---|---|---|---|---|
| Match Found Early | Arr = [15, 23, 7, 42, 9], Key = 7 | i=0 (15!=7), i=1 (23!=7), i=2 (7==7) | Match at i=2! Found=1, Break loop | Found at Index 2 (3 comparisons saved) |
| Key Not Found | Arr = [10, 20, 30], Key = 99 | i=0, 1, 2 all != 99 | Loop ends i=3 == N; Found=0 | Key not present in array |
⚡
Interactive C++ Compiler & Runner
Live In-BrowserEdit the code directly with the Edit Code button, provide custom inputs, and press Run Code to compile and execute in the live terminal console below!
📄
problem_8.cpp
GCC 13.2 • C++20
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cout << "Enter number of elements in array N: ";
if (!(cin >> n) || n <= 0) {
cout << "Invalid array size N!\n";
return 1;
}
vector<int> arr(n);
cout << "Enter " << n << " integers:\n";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
int key;
cout << "Enter target key to search: ";
cin >> key;
int foundIndex = -1;
int comparisons = 0;
// Linear search with early exit
for (int i = 0; i < n; ++i) {
comparisons++;
if (arr[i] == key) {
foundIndex = i;
break; // Early exit break
}
}
cout << "\n========================================\n";
if (foundIndex != -1) {
cout << "SUCCESS: Target key [" << key << "] FOUND at index " << foundIndex
<< " (Position " << (foundIndex + 1) << " in array).\n";
cout << "Comparisons executed : " << comparisons << " of " << n
<< " (" << (n - comparisons) << " comparisons saved!)\n";
} else {
cout << "FAILURE: Target key [" << key << "] NOT FOUND in the array.\n";
cout << "Comparisons executed : " << comparisons << " (Full scan completed).\n";
}
cout << "========================================\n";
return 0;
}
⌨️ Standard Input (cin):
Presets:
💻 Terminal Output
• Ready to run
Input: 5 15 23 7 42 9 7 Output: ======================================== SUCCESS: Target key [7] FOUND at index 2 (Position 3 in array). Comparisons executed : 3 of 5 (2 comparisons saved!) ========================================
Developer & Exam Key Takeaway
Early exit reduces average-case time to O(N/2) comparisons. For large datasets, early exit saves millions of CPU cycles.