fork download
  1. #include <stdio.h>
  2.  
  3. // **************************************************
  4. // Function: frequency
  5. //
  6. // Description:
  7. // Counts how many times the value x appears among the
  8. // first n elements of theArray (indices 0 .. n-1).
  9. //
  10. // Parameters:
  11. // theArray[] - array of integers to search
  12. // n - number of elements to check
  13. // x - integer value to count
  14. //
  15. // Returns:
  16. // frequency (int) - number of times x is found
  17. // **************************************************
  18. int frequency (int theArray[], int n, int x)
  19. {
  20. int frequency; /* how many times x is found */
  21.  
  22. frequency = 0; /* initialize count */
  23.  
  24. /* loop through every element in theArray */
  25. for (int i = 0; i < n; i++)
  26. {
  27. /* if the element x is found, increment frequency */
  28. if (theArray[i] == x)
  29. {
  30. frequency++;
  31. }
  32. }
  33.  
  34. return frequency;
  35. }
  36.  
  37. // **************************************************
  38. // Function: main
  39. //
  40. // Description:
  41. // Tests the frequency() function with a sample array.
  42. // **************************************************
  43. int main(void)
  44. {
  45. int theArray[] = {5, 7, 23, 8, 23, 67, 23};
  46. int n = 7;
  47. int x = 23;
  48.  
  49. int result = frequency(theArray, n, x);
  50.  
  51. printf("The value %d appears %d times in the array.\n", x, result);
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
The value 23 appears 3 times in the array.