Write C# program to count number of each element in an array


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. using System;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. int i, j, count, num;
  7.  
  8. int[] arr = new int[100];
  9. int[] frequency = new int[100];
  10.  
  11. //Reads size of the array
  12. Console.WriteLine("Enter size of the array: ");
  13. num = Convert.ToInt32(Console.ReadLine());
  14.  
  15. //Reads elements in array
  16. Console.WriteLine("Enter elements in the array: ");
  17. for (i = 0; i < num; i++)
  18. {
  19. arr[i] = Convert.ToInt32(Console.ReadLine());
  20. //Initially initialize frequency variable to -1
  21. frequency[i] = -1;
  22. }
  23.  
  24.  
  25. for (i = 0; i < num; i++)
  26. {
  27. count = 1;
  28. for (j = i + 1; j < num; j++)
  29. {
  30. //If duplicate element is found
  31. if (arr[i] == arr[j])
  32. {
  33. count++;
  34.  
  35. //Make sure not to count frequency of same element again
  36. frequency[j] = 0;
  37. }
  38. }
  39.  
  40. //If frequency of current element is not counted
  41. if (frequency[i] != 0)
  42. {
  43. frequency[i] = count;
  44. }
  45. }
  46.  
  47.  
  48. //Print frequency of each element
  49. Console.WriteLine("\nFrequency of all elements of array : \n");
  50. for (i = 0; i < num; i++)
  51. {
  52. if (frequency[i] != 0)
  53. {
  54. Console.WriteLine(arr[i] + " occurs " + frequency[i]+ " times");
  55. }
  56. }
  57.  
  58.  
  59. Console.ReadLine();
  60. }
  61.  
  62. }

Result

C# language techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.