Write a program which, given an integer array and its size, determines whether the array contains any value that is repeated at least once.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#define N 6

void swap(int *, int*);
void bubble(int *, int);  // Perform bubble sort
void determine_repeated(int *, int);

int main(int argc, char **argv) {

    int a[N] = {4, 4, 1, 4, 2, 1};
    bubble(a, N); // sort array in ascending order
    determine_repeated(a, N);
    return 0;
}

void determine_repeated(int a[], int n) {
    int prev = a[0], count = 0;
    for (int i = 1; i < n; i++)
    {
        if (a[i] == prev) count++;
        else
        {
           if (count != 0)
                printf("The value %d is repeated %d time(s)\n", prev, count);
            prev = a[i];
            count = 0;
        }
    }
    if (count != 0)
        printf("The value %d is repeated %d time(s)\n", prev, count);
}

void swap(int *n1, int *n2) {
    int tmp;
    tmp = *n1;
    *n1 = *n2;
    *n2 = tmp;
}

void bubble(int a[], int n) {

    for (int i = 0; i < n - 1; i++)
        for(int j = n - 1; j > i; j --)
            if(a[j - 1] > a[j])
                swap(&a[j - 1], &a[j]);
}

When you compile and execute the above program it produces the following result on Linux:

The value 1 is repeated 1 time(s)
The value 4 is repeated 2 time(s)

Brief Explanation

  • The program starts by initializing an array with some integer values.
  • Using the function bubble, the array is sorted in ascending order.
  • The function determine_repeated, determines if the array contains any value that is repeated at least once. The function prints the value and the number of times that it's repeated.

Add comment


Security code
Refresh