C# program to find the most frequent element

CsharpProgrammingServer Side Programming

Let’s say our string is −

String s = "HeathLedger!";

Now create a new array.

int []cal = new int[maxCHARS];

Create a new method and pass both the string and the new array in it. Find the maximum occurrence of a character.

static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}

Let us see the complete code −

Example

 Live Demo

using System;
class Demo {
   static int maxCHARS = 256;
   static void calculate(String s, int[] cal) {
      for (int i = 0; i < s.Length; i++)
      cal[s[i]]++;
   }

   public static void Main() {
      String s = "thisisit!";
      int []cal = new int[maxCHARS];
      calculate(s, cal);
      for (int i = 0; i < maxCHARS; i++)
      if(cal[i] > 1) {
         Console.WriteLine("Character "+(char)i);
         Console.WriteLine("Occurrence = " + cal[i] + " times");
      }
   }
}

Output

Character i
Occurrence = 3 times
Character s
Occurrence = 2 times
Character t
Occurrence = 2 times
raja
Published on 21-Aug-2018 13:23:22
Advertisements