Prime #### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime #### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# C program to find the frequency of element in an array

## Program to determine the occurence of elements in an given array.

In this program we will find the occurence of the unique element present in the given input array.

Let we have an array a[ ] = {1, 2, 2, 3, 2, 1}.

So the frequency of the distinct elements will be:

•   1 occurs 2 times
•   2 occurs 3 times
•   3 occurs 1 times. # Algorithm

To find the frequency of the elements in the array we can follow the following steps:

• Take the size of array from the user.
• Create the array of given size, and  take the values of the element from the user.
• Create one array that track the visited elements in the array, so that the duplicate printing can be avoided.
• Now using nested for loops we will count the frequency of every element in an array.

### C program based on above approach is given below:

`// C program to find the frequency of the elements in an array //#include<stdio.h>int main (){  int n;			// variable to store the size of an array.  printf ("Enter the size of the array : ");  scanf ("%d", &n);		// takes the size of the array from the user  int arr[n];			// Declare the array arr of size n that contains the elements of the array.  int visited[n];		// Declare the array named visited of n size to mark 1 for the visted elements.  // Takes the elements of the array from the user  printf ("\nEnter the elemnts o the array: ");  for (int i = 0; i < n; i++)    scanf ("%d", &arr[i]);  // Traversing the array and find print the frequency of the elements  for (int i = 0; i < n; i++)    {      // check if that element is visited or not      if (visited[i] == 1)	  continue;      int count = 1;		// variable that count the frequency of the arr[i] element.      for (int j = i + 1; j < n; j++)	  {	    if (arr[i] == arr[j])	      {	        count++;	        visited[j] = 1;	      }	  }      printf ("\n %d occurs %d times", arr[i], count);    }  return 0;}`
`Output:Enter the size of the array: 5Enter the elements of the array:1 2 3 2 11 occurs 2 times2 occurs 2 times3 occurs 1 times`

### Time and Space complexity :

• Time complexity – O(n^2)
• Space complexity – O(n)