C++ Code Example: searchs an array for a number

This code takes a user input number and searches for it in a pre-defined integer array numbers. It uses a for loop to iterate over the numbers array and compares each element with the number input. If a match is found, the boolean variable numberInArray is set to true and the loop is broken. The code then outputs whether the number was found in the array or not, based on the value of numberInArray.

The first line is a preprocessor directive that includes the standard input/output library in the code. The second line specifies the standard namespace to use in the program.

The main function is the starting point of the program. An integer variable number and two integer variables i and arrayLength are declared. A boolean variable numberInArray is declared and set to false, and an integer array numbers with 8 elements is defined.

The next part of the code outputs a prompt to the user asking for a number to search for and stores the user’s input in the number variable.

In the next line, arrayLength is calculated as the number of elements in the numbers array using the end and begin functions.

The next for loop iterates over the numbers array and compares each element with the number input. If a match is found, numberInArray is set to true and the loop is broken.

Finally, the code outputs either “found” or “not found” depending on the value of the numberInArray variable. The conditional operator ? is used to determine which string to output based on the value of numberInArray. If numberInArray is true, “found” is output; otherwise, “not found” is output.

#include <iostream>
using namespace std;

int main () {
    int number, i, arrayLength;
    bool numberInArray = false;
    int numbers[] = {65, 35, 23, 75, 76, 33, 12, 9};

    cout << "What number are you looking for " << endl;
    cin >> number;

    arrayLength = end(numbers) - begin(numbers);
    
    // loop over array and search for number
    for(int i = 0; i < arrayLength; i++) {
        if(number == numbers[i]) {
            numberInArray = true;
            break;
        }
    }

    // if boolean varible numberInArray is true ouput "found", 
    // if not output "not found"
    cout << (numberInArray ? "found" : "not found") << endl;
}