Search code examples
arraysc

Finding number of repeated elements in an array using C


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 size n. It first takes in a positive integer n from the user. Then reads n numbers and stores them in arr. It checks and prints the number of repetitions in arr. The result is the sum of the total number of repetitions in the array.
Example: If arr = [4,3,4,4,3,4,5]
Then number of repetitions is 6 (which is 4 repetitions of 4 + 2 repetitions of 3)

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)


Solution

  • To avoid over-counting, you will need to keep track of which numbers have already been repeated. I wold just have a second array to save "already repeated" values:

    #include <stdio.h>
    
    int main()
    {
        int n, p = 0, r = 0;
    
        printf("Enter the size of the array: ");
        scanf(" %u",&n);
        int arr[n];
        int rep[n - 1];
        for (int i = 0; i < n; i++) {
            printf("Enter arr[%d]: ",i);
            scanf(" %d",&arr[i]);
        }
        for (int i = 0; i < n; i++) {
            int count = 1, j;
            for (j = 0; j < r; j++) {
                if (arr[i] == rep[j])
                    break;
            }
            if (j < r)
                continue;
            for (j = i + 1; j < n; j++)
                if (arr[i] == arr[j])
                    count++;
            if (count > 1) {
                p = p + count;
                rep[r++] = arr[i];
            }     
        }
        printf("Number of repitions is %d\n",p);
    }