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
arrof sizen. It first takes in a positive integernfrom the user. Then readsnnumbers 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)
break?