HOME Forums Forum Counting Item in array

This topic contains 2 replies, has 1 voice, and was last updated by  Meng Meng 1 year, 2 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #968 Reply

    Tang Seakmeng

    Can anyone write this code for me!
    Example: array a[0] = 10
    a[1] = 20
    a[2] = 10
    Result: 10 occurs 2 times.
    20 occurs 1 times!

    #969 Reply

    Meng Meng

    static void Main()
    {
    Write(“Input number of element: “);
    int n = int.Parse(ReadLine());

    int[] a = new int[n];
    for (int i = 0; i < n; i++)
    {
    Write(“Input A[{0}]: “, i);
    a[i] = int.Parse(ReadLine());
    }

    Array.Sort(a);

    WriteLine(“After sorted this array: “);
    int j = 0;
    foreach (int e in a)
    {
    WriteLine(“A[{0}]: {1}”, j, a[j]);
    j++;
    }

    for (int i = 0; i < n; i++)
    {
    int time = 1;
    for (j = i + 1; j < n; j++)
    {
    if (a[i] == a[j])
    {
    time += 1;
    }
    }
    if (time > 1)
    {
    WriteLine(“{0} occurs {1} times.”, a[i], time);
    i += time – 1;
    }
    else
    {
    WriteLine(“{0} occurs {1} times.”, a[i], time);
    }
    }

    ReadKey();
    }

    #971 Reply

    Meng Meng
    static void Main(string[] args)
            {
                Write("Input number of element: ");
                int n = int.Parse(ReadLine());
    
                int[] a = new int[n];
                for(int i = 0; i < n; i++)
                {
                    Write("Input A[{0}]: ", i);
                    a[i] = int.Parse(ReadLine());
                }
    
                Array.Sort(a);
    
                WriteLine("After sorted this array: ");
                int j = 0;
                foreach(int e in a)
                {
                    WriteLine("A[{0}]: {1}", j, a[j]);
                    j++;
                }
                Count(n, a);
    
                    ReadKey();
            }
            private static void Count(int n, int[] a)
            {
                for (int i = 0; i < n; i++)
                {
                    int time = 1, j;
                    for (j = i + 1; j < n; j++)
                    {
                        if (a[i] == a[j])
                        {
                            time += 1;
                        }
                    }
                    if (time > 1)
                    {
                        WriteLine("{0} occurs {1} times.", a[i], time);
                        i += time - 1;
                    }
                    else
                    {
                        WriteLine("{0} occurs {1} times.", a[i], time);
                    }
                }
            }
Viewing 3 posts - 1 through 3 (of 3 total)
Reply To: Counting Item in array
Your information: