find a number in vector c++

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {2, 4, 6, 8, 10}; // Creating a vector of integers

    int searchNumber = 6; // Number to be searched

    bool found = false; // Initializing a boolean variable to track if the number is found

    // Iterating through the vector to find the searchNumber
    for (size_t i = 0; i < numbers.size(); ++i) {
        if (numbers[i] == searchNumber) { // Checking if the current element is equal to searchNumber
            found = true; // Setting found to true if the number is found
            break; // Exiting the loop since the number is found
        }
    }

    // Checking if the number is found and printing the result
    if (found) {
        std::cout << "Number " << searchNumber << " is found in the vector." << std::endl;
    } else {
        std::cout << "Number " << searchNumber << " is not found in the vector." << std::endl;
    }

    return 0;
}

Explanation:

  • #include <iostream>: Includes the necessary library for input/output operations.
  • #include <vector>: Includes the necessary library for using vectors in C++.
  • std::vector<int> numbers = {2, 4, 6, 8, 10};: Declares and initializes a vector named numbers containing integers {2, 4, 6, 8, 10}.
  • int searchNumber = 6;: Initializes the searchNumber variable with the value 6, which is the number to be searched in the vector.
  • bool found = false;: Initializes a boolean variable found to false which will track if the number is found or not.
  • for (size_t i = 0; i < numbers.size(); ++i) { ... }: Loops through each element of the vector using a for loop to check if the searchNumber exists within the vector.
  • if (numbers[i] == searchNumber) { ... }: Checks if the current element of the vector is equal to searchNumber.
  • found = true; break;: If the searchNumber is found in the vector, sets found to true and exits the loop using break.
  • if (found) { ... } else { ... }: Checks the value of found after the loop to determine if the searchNumber was found or not and prints the appropriate message to the console.

This program searches for a specific number within a vector of integers and prints whether the number is found or not in the vector.