Group
Arrays and Vectors in C++
Objective
1. Define an array with several integer values.
2. Create a function that takes the array and the target number as input.
3. Loop through the array and compare each element with the target number.
4. If the target number is found, print its index.
5. If the target number is not found, print a message stating it is not in the array.
6. Test the program with different arrays and target numbers.
Implement a program that searches for a number in an array.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to search for a number in an array
int searchNumber(int arr[], int size, int target) {
// Loop through the array to find the target number
for (int i = 0; i < size; i++) {
if (arr[i] == target) { // If the number is found
return i; // Return the index of the found number
}
}
return -1; // Return -1 if the number is not found
}
int main() {
// Define an array of numbers
int numbers[] = {1, 3, 5, 7, 9, 11};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
int target = 7; // Set the number to search for
// Call the function to search for the target number
int index = searchNumber(numbers, size, target);
// Check if the number was found and print the result
if (index != -1) {
cout << "Number " << target << " found at index " << index << endl;
} else {
cout << "Number " << target << " not found in the array." << endl;
}
return 0; // End of program
}
Output
Number 7 found at index 3