Loading your workspace…
Loading your workspace…
Read a one-dimensional array of integers and remove repeated values, keeping the first occurrence of each.
#include <stdio.h>
#define MAX 100
int main(void) {
int arr[MAX], unique[MAX];
int n, i, j, count = 0, found;
printf("Enter the number of elements (1-%d):\n", MAX);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
printf("Error: invalid size\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n; i++) {
found = 0;
for (j = 0; j < count; j++) {
if (unique[j] == arr[i]) {
found = 1;
break;
}
}
if (!found) {
unique[count] = arr[i];
count++;
}
}
printf("Array without duplicates:\n");
for (i = 0; i < count; i++) {
printf("%d ", unique[i]);
}
printf("\n");
return 0;
}
Input
7
1 2 2 3 1 4 3Output
Enter the number of elements (1-100):
Enter 7 integers:
Array without duplicates:
1 2 3 4Input
4
5 5 5 5Output
Enter the number of elements (1-100):
Enter 4 integers:
Array without duplicates:
5The output array is built as you go, so the check is always against values already kept. Scanning the output rather than the input means each value is compared only with the distinct values seen so far.
The loop is quadratic in the worst case, which is acceptable for a lab-sized array. Sorting first would be faster but would change the original order of the values.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
7 1 2 2 3 1 4 3
Expected output
Enter the number of elements (1-100): Enter 7 integers: Array without duplicates: 1 2 3 4
4 5 5 5 5
Expected output
Enter the number of elements (1-100): Enter 4 integers: Array without duplicates: 5
The output holds only distinct values, so a match there means the value is a duplicate.
O(n²), because each of n values may be compared with up to n kept values.
The program keeps values in the order they first appear, which is the natural reading of 'remove duplicates'.
It stops the search as soon as a duplicate is found.
Sort a copy and compare neighbours, or use a hash set; both change the work done but not the result.
Back to all RCU 21BCA1C1P lab programs.