Error counting repeated values in an array

Asked

Viewed 40 times

1

I’m trying to ask a question that counts the number of times each value appears on the array, which I tried, only counts a repeated number, someone could 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 that my code presents 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;
}

1 answer

1

You are not checking if the number already exists in the vector, if it already exists increment your counter and otherwise 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;
}
  • instead of vector.size() should use TAM, it indicated C and not C++

  • @prmottajr Thanks. I hadn’t noticed.

Browser other questions tagged

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