Error counting values repeated in a vector

1

I'm trying to make an issue count the number of times that each value appears in the vector, which I tried, just count a number repeated, could someone help me with logic, Example of input 8 10 8 260 4 10 10

Output 4 appears 1 time (s) 8 appears 2 time (s) 10 appears 3 time (s) 260 appears 1 time (s)

The output my code displays 4 appears 1 time My code

#include <stdio.h>

#define TAM 100

int main(int argc, char** argv)
{
   int vetor[TAM], num, fre[TAM] = {0};

   for(int i = 0; i < 7; i++)
   {
      scanf("%d", &num);
      ++fre[num];
      vetor[i] = num;
   }

   for(int i = 0; i < 7; i++)
   {
      printf("O numero %d se repete %d\n", vetor[i], fre[i]);
   }
  return 0;
}
    
asked by anonymous 25.04.2018 / 15:45

1 answer

1

You are not checking whether the number already exists in the vector, if it already exists, increment your counter and add it.

bool bNumeroJaExiste = false;
for (int j = 0; j < TAM && !bNumeroJaExiste; j++)
{
    //    O número já existe?
    if (num == vetor[j])
    {
        ++fre[j];    //    incrementa o contador na posição do número encontrado.
        bNumeroJaExiste = true;
    }
}

if (!bNumeroJaExiste)
{
    //  Adiciona o número no vetor.
    ++fre[i];
    vetor[i] = num;
}
    
25.04.2018 / 15:53