Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am doing a program that tells me which are even and which are not and which and how many numbers are repeated but does not give me how many numbers are repeated and I do not know which I am doing wrong this is my code

What I have tried:

C#
int num;
int entrada = Convert.ToInt16(Interaction.InputBox("¿Cuantos numeros vas a ingresar?", "Numeros"));
int[] lista = new int[entrada];
for (int t = 0; t < entrada; t++)
{
   num = Convert.ToInt16(Interaction.InputBox("Ingrese el numero" + (t + 1)));
   listBox1.Items.Add(num);

   if (Convert.ToInt16(num) % 2 == 0)
   {
      listBox2.Items.Add("Los numeros pares son" + num);
   }
   else
   {
      listBox2.Items.Add("Los numeros impares son" + num);
   }
   lista[t] = num;

   for (int i = 0; i < t; i++)
   {
      if (num== lista[i])
      {
         listBox2.Items.Add("Se repite el numero"  + lista[i]+"las veces que se repite son:"+i);
      }
   }
}

}
}
Posted
Updated 21-Jan-20 22:32pm
v3

There is a neat method for counting the instances of a number in an array using Linq. It may not be ideal when the count is taken every time an addition is made but it is useful when an inventory needs to be taken after multiple additions.

C#
List<int> list = new List<int> { 1, 2, 3, 2, 3, 3 };
Dictionary<int, int> inventory= list.GroupBy(x => x).ToDictionary(g => g.Key,g => g.Count());
foreach (KeyValuePair<int, int> entry in inventory)
  {
   Console.WriteLine($"Number: {entry.Key} Instances: {entry.Value}");
  }

 
Share this answer
 
If I'm interpreting the code correctly, the inner for loop is supposed to count the instances of a specific number? If that is correct, you now just add as many items into the listbox as the number is found. You probably want to first count the number of instances and then add it to the list.

Something like
C#
   ...
   lista[t] = num;

   int numberCount = 0;
   for (int i = 0; i <= t; i++)
   {
      if (num == lista[i])
      {
         numberCount++;
      }
   }
   listBox2.Items.Add($"Se repite el numero {num} las veces que se repite son: {numberCount}");
...
 
Share this answer
 
v2
Comments
George Swan 21-Jan-20 17:22pm    
Shouldn't that be i < t+1; ?
Wendelius 21-Jan-20 22:56pm    
Good point, thank you!
Wendelius 21-Jan-20 22:56pm    
Comparison now changed

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900