I have to make an array of n elements, and find out how many times each number appears, like this:
Array: (-1.7 ; 3.0 ; 0.0 ; 1.5 ; 0.0 ; -1.7 ; 2.3 ; -1,7)
-1.7 appears 3 times
3.0 appears 1 time
0.0 appears 2 times
1.5 appears 1 time
2.3 appears 1 time
I have tried it, and my code looks like this:
int n = 0;
Console.WriteLine("Type in the size of your array...");
n = int.Parse(Console.ReadLine());
float[] vet = new float[n];
int[] freq = new int[n];
Console.WriteLine("Now, type in each element...");
for(int i = 0; i < vet.Length; i++)
{
Console.Write("Position {0}: ", i);
vet[i] = float.Parse(Console.ReadLine());
}
for(int j = 0; j< vet.Length; j++)
{
for(int k = 0; k< freq.Length; k++)
{
if(vet[j] == vet[k])
{
freq[j]++;
}
}
}
Console.WriteLine("The number of times each element appears in the array is:");
for(int l = 0; l< freq.Length; l++)
{
Console.WriteLine("{0} appears {1} time(s)", vet[l], freq[l]);
}
Console.ReadKey();
But the output stays like this:
The number of times each element appears in the array is:
-1.7 appears 3 time(s)
3.0 appears 1 time(s)
0.0 appears 2 time(s)
1.5 appears 1 time(s)
0.0 appears 2 time(s)
-1.7 appears 3 time(s)
2.3 appears 1 time(s)
-1.7 appears 3 time(s)
My question is: How can I make my code works in a way that repeated numbers are printed once, like the first example?