fork download
  1. #include <stdio.h>
  2.  
  3. /* ==================================================
  4.  * Function Prototype
  5.  * ================================================== */
  6. int frequency (int theArray[], int n, int x);
  7.  
  8. /* ==================================================
  9.  * Test Driver (main)
  10.  * ================================================== */
  11.  
  12. // **************************************************
  13. // Function: main
  14. //
  15. // Description:
  16. // Tests the frequency() function with the provided
  17. // example where x = 23 appears 3 times.
  18. //
  19. // Parameters:
  20. // (none)
  21. //
  22. // Returns:
  23. // 0 on successful execution
  24. //
  25. // Notes:
  26. // - Uses only integers.
  27. // **************************************************
  28. int main(void)
  29. {
  30. int data[] = {5, 7, 23, 8, 23, 67, 23};
  31. int n = 7;
  32. int x = 23;
  33.  
  34. int result = frequency(data, n, x);
  35. printf("frequency of %d in first %d elements = %d (expected 3)\n",
  36. x, n, result);
  37.  
  38. /* Extra quick checks */
  39. printf("freq of 7 = %d (expected 1)\n", frequency(data, n, 7));
  40. printf("freq of 99 = %d (expected 0)\n", frequency(data, n, 99));
  41.  
  42. return 0;
  43. }
  44.  
  45. /* ==================================================
  46.  * Function Implementation
  47.  * ================================================== */
  48.  
  49. // **************************************************
  50. // Function: frequency
  51. //
  52. // Description:
  53. // Counts how many times the value x appears in the
  54. // first n elements of theArray.
  55. //
  56. // Parameters:
  57. // theArray[] - array of integers to search
  58. // n - number of elements to examine (0..n-1)
  59. // x - value to count within theArray
  60. //
  61. // Returns:
  62. // frequency - number of times x appears among the first n elements
  63. //
  64. // Notes:
  65. // - If n <= 0, the function returns 0.
  66. // - Caller must ensure n does not exceed the array's actual length.
  67. // **************************************************
  68. int frequency (int theArray[], int n, int x)
  69. {
  70. int frequency; /* how many times x is found */
  71. int i; /* loop counter */
  72.  
  73. frequency = 0; /* initialize count */
  74.  
  75. /* loop through every element in theArray up to n (exclusive) */
  76. for (i = 0; i < n; i++)
  77. {
  78. /* if the element equals x, increment frequency */
  79. if (theArray[i] == x)
  80. {
  81. frequency++;
  82. }
  83. }
  84.  
  85. return frequency;
  86. }
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
frequency of 23 in first 7 elements = 3 (expected 3)
freq of 7  = 1 (expected 1)
freq of 99 = 0 (expected 0)