In this tutorial, you will learn how to write C program to print all the repeated numbers with frequency in an array.
The Complete logic behind findings duplicate elements in array is:
- In this program our focus is to calculate the occurrence of each number given by the user in an array.
- So We have tried to make this program very simple.
- Our program will take inputs from the users between 1 to 100 in one array.
- And in second array we are storing the occurrence of number.
- For the occurrence we are increasing the value by one for the index which is equal to the number given by user.
- For example first time at index 3 value is 0. Now user have given 3 first time as a input then we will increase count by 1 at the index 3 for array.
- Now again user has given 3 as an input then we will again increase the count by 1 for index 3 and now count become 2.
- So we can say that occurrence of 3 is 2 times.
How our program will behave?
As we have already seen our logic above for finding the occurrence of numbers.
Our program will take an array as an input.
And on the basis of inputs it will perform some operation to count the occurrence of all numbers.
We will see it below
Program to count the occurrence of numbers in an array
#include<stdio.h>
#include<conio.h>
void main(){
int i,n=1;
printf("enter the size of an array : ");
scanf("%d",&n);
int arr[n];
int occur[100] = {0};
printf("please give value to insert in array: n");
for(i=1;i<=n;i++){
scanf("%d",&arr[i]);
occur[arr[i]]++;
}
printf("repeated number is : ");
for(i=1;i<=n;i++){
printf("%d is repeated %d times n",i,occur[i]);
}
getch();
}
Output:
Explanation of above program to find the occurrence of numbers in array in c
- In the above program we have two variables i and n. n is to take size of array as an input.
- Also we have two arrays arr and occur of type integer. arr to take elements as input and occur is to store the occurrence of particular number.
- Now main operation is performing in for loop.
- We are taking array element as an input and on the basis of input we are increasing the count at index number as per input value.
- Suppose if 3 is given as an input then for the array occur we will increase value by 1 at index 3.
- With this logic our each index of occur array have now the count of the occurrence of number.
- And at last we have iterated the array and printed the occurrence.
This was the all logic behind counting the duplicate or occurrence of numbers in array.