I am unable to find the correct logic to find the number of repeated elements in an array. I can understand why my logic is not working, but I am not able to overcome it.
Following is the actual question:
Write a program that declares an integer array
arr
of sizen
. It first takes in a positive integern
from the user. Then readsn
numbers and stores them inarr
. It checks and prints the number of repetitions inarr
. The result is the sum of the total number of repetitions in the array.
Example: Ifarr
=[4,3,4,4,3,4,5]
Then number of repetitions is6
(which is 4 repetitions of4
+ 2 repetitions of3
)
Following is my code:
#include <stdio.h>
int main() {
int n, i, j, count = 1, p = 0;
printf("Enter the length of array");
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i++) {
printf("Enter a number\n");
scanf("%d", &arr[i]);
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
break;
}
}
if (count != 1) {
p = p + count;
count = 1;
}
}
printf("Number of repetitions are %d", p);
}
For the above code if we take the array as mentioned in the question, then each time my code encounters two same 4's, it counts both of them, hence my program ends up counting extra number of 4's. So I am unable to find some better logic to over come it.
(I am a beginner so I doesn't no much advanced function/methods used in C)
One of the things that you can do is, keep an extra array for the numbers you have checked and each time when you compare numbers you would check if you have already seen this number or not.
I also want to include a few another approach to this problem. If we know that numbers in the list won't be so big we can use an array to keep track of counts.
//numbers = {4, 3, 4, 4, 3, 4, 5}
int max = findMaxValue(numbers);
int counts[max]; //should be done with dynamic memory allocation
for(i=0;i<max;i++){
counts[max] = 0;
}
for(i=0;i<numbers.size;i++){
counts[numbers[i]]++;
}
int sum = 0;
for(i=0;i<max;i++){
if(counts[i] > 1){
sum += counts[i];
}
}
Another thing that you can do is, sort the numbers first and then compare adjacent elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With