Question


Q1. Write a C Program to print the duplicate elements of an array.
In this program, you need to print the duplicate elements present in the array.

Answers

There are no human answers yet.
Answered by GPT-4o mini
Certainly! Below is a simple C program that takes an array of integers, checks for duplicate elements, and prints them out.

```c
#include <stdio.h>

int main() {
int arr[100], n, i, j;
int isDuplicate;

// Read the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

// Read the elements of the array
printf("Enter the elements:\n");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Duplicate elements in the array are: ");
int foundDuplicate = 0; // Flag to check if any duplicate has been found

// Check for duplicate elements
for(i = 0; i < n; i++) {
isDuplicate = 0; // Reset duplicate flag for new element
for(j = 0; j < i; j++) {
if(arr[i] == arr[j]) {
isDuplicate = 1; // Mark as a duplicate
break;
}
}
if(isDuplicate) {
// Check if we've already printed this duplicate
if (!foundDuplicate) {
printf("%d ", arr[i]);
foundDuplicate = 1; // Set the flag after finding the first duplicate
}
}
}

if (!foundDuplicate) {
printf("No duplicates found.");
}

printf("\n");
return 0;
}
```

### Explanation:
1. **Input Handling**: The program starts by asking the user for the number of elements in the array and then reads the elements.
2. **Duplicate Checking**:
- We use two nested loops to compare each element with the others before it.
- If a duplicate is found, it checks if it has been printed before to avoid printing the same duplicate multiple times.
3. **Output**: Finally, it prints out the duplicate elements or states that none were found.

### How to Compile and Run:
You can copy this code into a C file, say `find_duplicates.c`, then compile and run it using:

```bash
gcc find_duplicates.c -o find_duplicates
./find_duplicates
```

Make sure you have a C compiler like `gcc` installed on your system.

Related Questions