In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of March 31st
(this exercise will still be available for submission after that deadline, but without couting towards your grade)
[to understand the context of this problem, you should read the class #04 exercise sheet]


In this problem you should submit a file containing the function as described (without any main function). Inside the function do not print anything that was not asked!

[PII026] Counting Occurrences

Will Byers has a bad feeling again… The Mind Flayer is trying to break into the real world, and strange signals are appearing in Hawkins. To stop it, Will needs to decode a hidden numerical sequence that appears in his visions.

He has an array a[] of n integers, and one specific number x keeps showing up in his dreams. He believes that counting how many times x appears in the array will help him and his friends find a way to defeat the Mind Flayer.

The Problem

Write a function int count(int x, int a[], int n) that receives an integer x and an array a[] of size n and returns the number of times x occurs in the array.

Constraints

The following limits are guaranteed in all the test cases that will be given to your program:

1 ≤ x ≤ 100       Number to count occurrences
1 ≤ a[i] ≤ 100       Numbers in the array
1 ≤ n ≤ 100       Size of the array

Submission

You should submit a .c file containing the requested function, without any main function and without printing anything. You can however create additional methods, if you need them.

Mooshak will use the following code to link to your function, read the inputs and call your method, printing its result.

#include <stdio.h>

// Forward declaration of function to implement
int count(int, int [], int);

int main(void) {

  // Read array of n integers
  int n;
  scanf("%d", &n);
  int a[n];
  for (int i=0; i<n; i++)
    scanf("%d", &a[i]);

  // Print the array (assume size >= 1)
  printf("a = [%d", a[0]);
  for (int i=1; i<n; i++)
    printf(",%d", a[i]);
  printf("]\n");

  // Read q queries and for each call the count function
  int q;
  scanf("%d", &q);
  for (int i=0; i<q; i++) {
    int x;
    scanf("%d", &x);
    printf("count(%d, a, %d) = %d\n", x, n, count(x, a, n));
  }
  
  return 0;
}

Example Input Example Output
10
1 1 4 5 2 5 1 2 1 2
5
1 2 3 4 5
a = [1,1,4,5,2,5,1,2,1,2]
count(1, a, 10) = 4
count(2, a, 10) = 3
count(3, a, 10) = 0
count(4, a, 10) = 1
count(5, a, 10) = 2

Programming II (CCINF1002)
DCC/FCUP - University of Porto