Count Repeated Elements in an Array in C Programming is generally asked in interviews.
This problem can be solved in any language.
Here we will discuss algorithms to count repeated elements and implement them in C programming.
What is Repeated Elements
Repeated elements are elements that occur more than one time in a list or in a sequence.
Consider the following list
1 2 3 4 5 6 7 7 2 3 3 3
Here element 2 is repeating 2 times 3 is repeating 4 times and 7 is repeating 2 times.
This thing we have to implement in programming.
So our input is a list or sequence of elements.
and output is repeated details and repetition numbers.
So how will we turn our input into output?
Algorithm to Count Repeated Elements
Let’s define our Algorithm that will get input and give us the desired output.
- Create Array arr[] and repeated[][]
- Take input from the user and store it to arr
- For each element of the arr check is it in the repeated array or not
- If an element is found then increase the element count
- Else add an element to the repeated array
- The print repeated array that has count 2 or more
Above is our simple step to developing our program
Program to Count Repeated Elements in C Programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include<stdio.h> int main() { int arr[20]; int repeated[20][2]; int elementCount = 0; int count = 0; int found = 0; int position = 0; int i = 0, j = 0; printf("\nEnter size of an array\n"); scanf("%d", & count); for (i = 0; i < count; i++) { printf("Enter element\n"); scanf("%d", & arr[i]); } for (i = 0; i < count; i++) { for (int j = 0; j <= elementCount; j++) { if (arr[i] == repeated[j][0]) { found = 1; position = j; break; } } if (found == 1) { repeated[position][1] += 1; } else { repeated[elementCount][0] = arr[i]; repeated[elementCount][1] = 1; elementCount++; } } printf("\nRepeated Elements are \n "); printf("\nElement No of Repeatatione\n "); for (i = 0; i < elementCount; i++) { if (repeated[i][1] > 1) { printf("\n%d\t\t\t %d", repeated[i][0], repeated[i][1]); } } } |
Based on the above algorithm we develop this program.
Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | Enter size of an array 15 Enter element 1 Enter element 2 Enter element 3 Enter element 4 Enter element 5 Enter element 6 Enter element 4 Enter element 4 Enter element 3 Enter element 1 Enter element 1 Enter element 3 Enter element 1 Enter element 5 Enter element 6 Repeated Elements are Element No of Repetition 1 4 3 3 4 3 5 2 6 2 |
Hope you learn from this example.