Write a C program to find the duplicate element in an array?

Find the duplicate number in array: For example, an array with length 5 contains numbers {1, 2, 3, 4, 4}, the duplicated number is 4. Suppose that the duplicated number in the array is m in given example. The sum of all numbers in the array, denoted as arrSum, should be the result of 1+2+...+(n-1)+m. It is not difficult to get the sum of 1+2+...+(n-1), which is denoted as sum. The duplicated number m will be the difference of arrSum and sum. Following C program demonstrates how do we detect a repeated element in an integer array?.

/* An array of size N contains numbers ranging from 1 to N-1.
   There is exactly one number is duplicated in the array.
   Write a C program to find the duplicated number?
*/
#include <stdio.h>
#define N 5
int main()
{
  int arr[N]; //contains integers from 1 to N-1
  int arrSum = 0; //sum of array elements
  int sum = (N * (N - 1)) / 2; //sum of 1 to N-1
  int i; //loop counter
  printf("Enter %d integers form 1 to %d, with one duplicate:", N, N-1);
  for (i = 0; i < N; i++)
  {
    scanf ("%d", &arr[i]);
    arrSum += arr[i];
  }
 
  printf("\nDuplicate number is: %d\n", arrSum - sum);
}



Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Bees 'go online' in ManchesterPosted on Friday September 22, 2017

Rory visits a beekeeper in Manchester who is gluing wireless chips to his bees.

The long wait for a Persian iPhone keyboardPosted on Friday September 22, 2017

The new Apple's iOS has Persian keyboard. BBC Persian's Sam Farzaneh discusses why it is an important feature.

Uber London loses licence to operatePosted on Friday September 22, 2017

Ride-hailing app Uber is "not fit and proper" to operate in London, the transport regulator says.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×