Search for a Number in an Array

Search for a Number in an Array

In this exercise, you will create a program that searches for a specific number in an array. Searching is a fundamental operation used for finding values, validating inputs, and performing data analysis.

The goal is to implement a Linear Search algorithm. You will iterate through the array, compare each element with a target value, and determine its position or existence.

Logic Components

1. Comparison

We use the == operator inside a loop to check if the current element matches the target number.

2. Early Exit

Once the number is found, we immediately return the index to stop unnecessary iterations.

3. Sentinel Value

If the loop finishes without finding the target, we return -1 as a standard signal for "Not Found".

Learning Objectives

  • 1. Declare and initialize an integer array with sample data.
  • 2. Create a modular function searchNumber to handle the logic.
  • 3. Practice the search pattern using conditional loops.
  • 4. Output the search result clearly in the console.

Solution Implementation

search_array.cpp Algorithms
#include <iostream>
using namespace std;

// Function to search for a number in an array
int searchNumber(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i; 
        }
    }
    return -1;
}

int main() {
    int numbers[] = {1, 3, 5, 7, 9, 11};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int target = 7; 

    int index = searchNumber(numbers, size, target);

    if (index != -1) {
        cout << "Number " << target << " found at index " << index << endl;
    } else {
        cout << "Number " << target << " not found." << endl;
    }

    return 0;
}

Console Output:

Number 7 found at index 3
Related Topics
Linear Search Conditional Iteration Function Return Codes Index Management

Share this Training

Help your friends learn C++ array logic!

© C++ Programming Exercises. Master the art of performance coding.