15,922,315 members
1.00/5 (1 vote)
See more:
Hi ,

I have an array like

ar[]={5,7,3,5,3,6,5,2,1}

in this i want to print the number which has maximum occurrence
o/p=5 (because it has occurred 3 times in array)

and also do the sorting in descending order

1,2,3,5,6,7

Posted
Updated 6-Mar-14 2:07am
v2
CHill60 6-Mar-14 8:08am
What have you tried so far?
ZurdoDev 6-Mar-14 8:10am
Where are you stuck?
richa11 6-Mar-14 8:28am
I have sorted the array in descending order but not able to print the maximum ocurrence

## Solution 1

This should work actually,
C#
`var max = ar.GroupBy(x => x).MaxBy(x => x.Count()).First().Key;`

and for Descending order,
C#
`var max = ar.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key;`

Let me know if it is not working. :)
See this link[^] as well.

-KR

v2
richa11 6-Mar-14 8:26am
Thanks Rohit..

But I have to use only loops in this
Krunal Rohit 6-Mar-14 8:30am
int[] temp = new int[ar.Length];
for(int i=0; i<ar.length; i++)
temp[i] = ar[i];
}

Try this, I might be wrong.

-KR
richa11 6-Mar-14 8:33am
static void Main()
{
int[] ar = { 8, 5, 3, 5, 8, 5, 2, 1 };
int temp;
int count = 1;
int[] temparr = new int[ar.Length];
for (int i = 0; i < ar.Length; i++)
{
for (int j = i + 1; j < ar.Length; j++)
{
if (ar[i] < ar[j])
{
temp = ar[j];
ar[j] = ar[i];
ar[i] = temp;
}
}

}
for (int i = 0; i < ar.Length; i++)
{
Console.WriteLine(ar[i]);
}
Console.WriteLine("--------------");
for (int i = 0; i < ar.Length; i++)
{

for (int j = 1 ; j < ar.Length; j++)
{
if (ar[i] == ar[j])
{
count++;

}
if (count > 1)
{
temparr[i] = count;

}
count = 1;

}
}
Here is my code,

## Solution 2

C#
`int[] array = { 5, 7, 3, 5, 3, 6, 5, 2, 1 };`

Sort by ascending first, then reverse array
C#
```Array.Sort(array);
Array.Reverse(array);
foreach (var item in array) { Console.Write(item); }```

To find which number has max occurencies try this:
C#
```var numOccurrencies = new Dictionary<int, int>();
int numberWithMaxOccurrencies = 0;
int maxOccurrences = 0;
foreach (var item in array)
{
if (!numOccurrencies.ContainsKey(item))
{
}
numOccurrencies[item]++;
if (numOccurrencies[item] > maxOccurrences)
{
numberWithMaxOccurrencies = item;
maxOccurrences = numOccurrencies[item];
}
}
Console.WriteLine("Number {0} has {1} occurrencies.", numberWithMaxOccurrencies, maxOccurrences);```

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

Top Experts
Last 24hrsThis month
 Ștefan-Mihai MOGA 25 Wendelius 20 Member 10231707 10 Dave Kreskowiak 6 CHill60 5
 Pete O'Hanlon 995 OriginalGriff 916 Dave Kreskowiak 499 Richard Deeming 340 Richard MacCutchan 320

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