0

I'm newbie. I want count frequency when I input numbers by use dictionary. Because I use array[100]. Size of array: 3 Input: 1 2 3 Result: 1: 1 time 2: 1 time 3: 1 time 0: 97 times

Please help me ! Run result

Implement code:

 {
        Console.WriteLine("Count frequencies of array: ");

        int[] arr = new int[100];
        int n, i;

        Console.Write("Input the number of elements to be stored in the array :");
        n = Convert.ToInt32(Console.ReadLine());

        Console.Write("Input {0} elements in the array :\n", n);
        for (i = 0; i < n; i++)
        {
            Console.Write("element - {0} : ", i);
            arr[i] = Convert.ToInt32(Console.ReadLine());

        }

        //Create a dictionary to store the counts.
        Dictionary<int, int> valCount = new Dictionary<int, int>();

        foreach (int x in arr)

        {
            if (valCount.ContainsKey(x))
                valCount[x]++;
            else
                valCount[x] = 1;
        }


        foreach (KeyValuePair<int, int> kvp in valCount)

            Console.WriteLine("{0}: " + "{1} times", kvp.Key, kvp.Value);

        Console.Write("Press any key to close the console app...");
        Console.ReadKey();
    }
1
  • But what is the actual issue? What are the expected results? Apr 1, 2020 at 8:51

1 Answer 1

0

Since you are using fixed size array, foreach loop will always iterate 100 times.

As I see in your code, you first gets input how much inputs you will accept as n. So you may use it to limit the count of the loop. Like:

for (int i = 0; i < n; i++)
{
    if (valCount.ContainsKey(x))
        valCount[x]++;
    else
        valCount[x] = 1;
}
1
  • I see. Thank you a lot !
    – Spencer
    Apr 1, 2020 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.