Print vector disregarding repeated values

3
  

Make an algorithm that reads a vector of 50 elements and prints the vector   disregarding the repeated values.

The code is giving the correct output, but if I type a repeated number, the program asks for a new one until I enter one that does not yet exist in the vector. How do I fix this?

int main(){
int vet[5], i, j, num;
for(i = 0; i < 5; i++){
     cout << ("Numero: ");
     cin >> vet[i];
     num = vet[i];
     for(j = 0; j < i; j++){
        if (vet[j] == num){
            --i;
            }
        }
     }

for(i = 0; i < 5; i++){
    cout << vet[i] << endl;
}
return 0;
}
    
asked by anonymous 15.10.2014 / 17:38

1 answer

4

I will consider the statement to be exactly this. You are not doing what the statement asks. Note that it has two parts:

  • "read a vector of 50 elements" (you are doing much more than this in loop which should be very simple;
  • "print the vector disregarding the repeated values" (you are printing everything).
  • It may sound silly, but it makes a difference. Programming is like this, you have to be attentive to every detail. Here in this second loop is that you should check if a value already exists.

    By solving this, you will not automatically have the problem of loop getting stuck.

    Without changing much and not optimizing the best way (but optimized in the most obvious way) I did a quick test that solves the way it was proposed. I did not do any extensive testing. I also did not modify your code very much or improved the formatting of the output, I think you know how to turn.

    #include <iostream>
    using namespace std;
    #define MAX_ITENS 50 //número de itens a serem lidos se quiser modificar para testes
    
    int main() {
        int vet[MAX_ITENS];
        bool repetido;
        for(int i = 0; i < MAX_ITENS; i++) {
             cout << ("Numero: ");
             cin >> vet[i];
        }
        for(int i = 0; i < MAX_ITENS; i++) {
            repetido = false;
             for(int j = 0; j < i; j++) { //verifica se existem iguais apenas entre os anteriores
                 if (vet[j] == vet[i]) {
                    repetido = true;
                    break; //tem repetido, não precisa continuar com a procura
                 }
             }
             if (!repetido) {
                 cout << vet[i] << endl;
             }
        }
    }
    

    See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

        
    15.10.2014 / 18:33