Helps in the logic of conditions and repetition in C++

Asked

Viewed 64 times

1

I have the following verification code to know if a certain number belongs to a vector. I couldn’t think of a more precise way to get the program to say that the number DOES NOT belong to the vector, just that it belongs and its position within it. Can you help me get the "number is not part of the array" message displayed after the check? (in a more streamlined 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;
}

1 answer

2


You can control this with a variable achou that begins as false and when he finds the number sought, changes to true. After the for, if the variable achou for 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 inside the vector, it will show the message it found for each occurrence. If this behaviour is not desired, just add a break; shortly after the achou = true;.

See here working on ideone.

  • I had thought about using another if, but I didn’t know how. It was too good this explanation, because I didn’t know how to use variables like Boolean. Thank you Victor Stafusa!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.