Print duplicate elements of an array in C programming language

#include <stdio.h>

int main(void)
{
	int arr[100];
	int size, flag = 0, i, j;
	scanf("%d", &size);
	for (i = 0; i < size; i++)
	{
		scanf("%d", &arr[i]);
	}
	for (i = 0; i < size; i++)
	{
		for (j = i + 1; j < size; j++)
		{
			if (arr[i] == arr[j])
			{
				flag = 1;
				break;
			}
		}
		if (flag == 1)
		{
			printf("%d \n", arr[i]);
		}
		flag = 0;
	}
	return 0;
}

this is a code to duplicate array elements. i am facing runtime error.

Kindly help me with correct code.

Code is working fine
please check here
https://onlinegdb.com/rkgkCgq7S

@includehelp Code is not actually correct something wrong in this code as duplicate values are not printing properly like if there are 3 duplicate values then the code should print 3 values but it’s printing one less value.

I tested it with the 3 duplicate values and it was working fine…
8 - SIZE INPUT
11 - ELEMENT1
22 - ELEMENT2
33 - ELEMENT3
11 - ELEMENT4
22 - ELEMENT5
33 - ELEMENT6
44 - ELEMENT7
55 - ELEMENT8
11 - duplicate 1
22 - duplicate 2
33 - duplicate 3

please share your user input values on which the output is wrong.

Dear @Pathikrit_Dutta,
You have done one mistake in the nested loop when you are finding duplicate values.
In that loop j is iterating till size-1 as well as i is also iterating till size-1 , which may give you run time error because you are iterating j out of bound, so i should iterate size-2,
that means the loop will be:
for (i =0; i<size-1; i++)
Doing this, if size of array is 5 then i will iterate till 0 to 3 and j will iterate 0 to 4.
If you don’t do this, your output will be wrong for some test cases.

@7H3R3DH47 @includehelp

2 Likes