Help on logic conditions and repetition in C ++

1

I have the following verification code to know if a certain number belongs to a vector. I could not think of a more accurate way to make the program say that the number DOES NOT belong to the vector, just that it belongs and what its position within it. Can you help me get the message "number is not part of the vector" after verification? (in a leaner way)

Code:

#include <iostream>

using namespace std;

int main()
{
    int vetor[5] = {10, 20, 30, 40, 50};
    int N;
    cout << "digite um numero: " << endl;
    cin >> N;

    for(int i = 0; i <=4; i++)
    {
        if(N == vetor[i])
            cout << "O numero faz parte do vetor e está na " << i+1 << " posicao" << endl;
    }
    return 0;
}
    
asked by anonymous 04.08.2017 / 05:36

1 answer

2

You can control this with a achou variable that starts as false and when it finds the searched number, it changes to true . After for , if the variable achou is false is because the number was not in the vector.

#include <iostream>

using namespace std;

int main() {
    int vetor[5] = {10, 20, 30, 40, 50};
    int n;
    cout << "Digite um número: " << endl;
    cin >> n;
    bool achou = false;

    for (int i = 0; i <= 4; i++) {
        if (n == vetor[i]) {
            cout << "O número " << n << " faz parte do vetor e está na posição " << (i + 1) << "." << endl;
            achou = true;
        }
    }

    if (!achou) {
        cout << "O número " << n << " não faz parte do vetor." << endl;
    }

    return 0;
}

Another detail to note is that if the same number appears more than once within the vector, it will show the message it found for each occurrence. If this behavior is not what is desired, just add break; soon after achou = true; .

See here working on ideone.

    
04.08.2017 / 06:19