Comparing a number with an array of numbers

I want to write a code wherein I have to compare a number with all the elements of an array. The number can be equal to only one element of an array or not equal to any element. I can compare the number with each element of the array using if statement inside a for loop. Problem is when I want to write "the number is not equal to any of the element of the array".The code shown below will execute the else statement 99 or 100 times, but I need that to be executed only once, after number is compared with all X[i] and not found equal.

for(int i=0;i<100;i++)
{cout<<"number is equal to one of the numbers in array"<<endl;}
{cout<<"number is not equal to any number in the array"<<endl;}}


  • There are a couple of things that you can do here:

    1. The reason it will iterate 100 times is because you are putting in a for loop and explicitly telling it too loop 100 times (0-99, since base index is 0). If it finds a number that matches an element in the array it will print your statement, but continue looping because you aren't telling it to exit the loop if it a match is found. To fix this, assuming it is in its own function, add a return to the if statement when the numbers match so it will exit the loop.

    The second thing you can do is, instead of using an if statement inside of a for loop, you can use a while loop. Something along the lines of:

    int i = 0;
    while( number != X[i] )

    what this does is loop until number is equal to an element in the array, and if is not equal to an element in the array you increment to the next element of the array.

    I may have misinterpreted your question, so lmk if that helped

  • Thanks for your descriptive analysis. It helped.

  • @Enrique Rueda said:
    int i = 0;
    while( number != X[i] )

    Your while loop is wrong:
    1. It will never finish. Due to x[i]++ it will loop forever.
    2. Even if point 1 was correct (x[i++]) it would still loop forever and/or spit OOB errors in case the checked number is not in array. Never use while like this.

    for loop is better in most cases as in this case, you just have to know the size of array beforehand or do something like this sizeof(array)/sizeof(array[0]) to get the size of it.

    @Ajib Paudel
    As for the case when the number is not in array just use helper variable. For example:

    bool found = false;
    for (int i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
        if (x[i] == number) {
            cout << "number is in array" << endl;
            found = true;
            break; // no need to loop through the rest
    if (!found) {
        cout << "number is not in array" << endl;
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!