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 namednumbers
containing integers{2, 4, 6, 8, 10}
.int searchNumber = 6;
: Initializes thesearchNumber
variable with the value6
, which is the number to be searched in the vector.bool found = false;
: Initializes a boolean variablefound
tofalse
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 afor
loop to check if thesearchNumber
exists within the vector.if (numbers[i] == searchNumber) { ... }
: Checks if the current element of the vector is equal tosearchNumber
.found = true; break;
: If thesearchNumber
is found in the vector, setsfound
totrue
and exits the loop usingbreak
.if (found) { ... } else { ... }
: Checks the value offound
after the loop to determine if thesearchNumber
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.