Removing duplicate items from an array using C language

Viewed 90

Removing duplicate items from a sorted array

#include <stdio.h>
#include <stdlib.h>

int main() {
    int arr[12] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5 };
    int temp[12];
    int i, j, k, n = 12;

    for (i = 0; i < n - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            temp[j] = arr[i];
            j++;
        }
    }

    temp[j] = arr[n - 1];

    for (k = 0; k <= j; k++) {
        printf("%d\n", temp[k]);
    }

    return 0;
}

Output:

6356652
1955753237
1956070172
6356716
1955750536
8
1955687363
1955687354
1
2
3
4
5

Process returned 0 (0x0)   execution time : 0.014 s
Press any key to continue.

I do not want these numbers to be printed out:

6356652
1955753237
1956070172
6356716
1955750536
8
1955687363
1955687354
2 Answers

You did not initialize the variable j. So using the uninitialized variable invokes undefined behavior.

It is better to form the array without duplicates in one loop instead of splitting the loop into a loop and one more statement after the loop.

You can write a separate function for example the following way as it is shown in the demonstrative program.

#include <stdio.h>

size_t remove_copy( const int a[], int b[], size_t n )
{
    size_t j = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        if ( i == 0 || a[i] != b[j-1] ) b[j++] = a[i];
    }

    return j;
}

int main(void) 
{
    int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5 };
    int b[sizeof( a ) / sizeof( *a )];
    const size_t N = sizeof( a ) / sizeof( *a );

    for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
    putchar( '\n' );

    size_t n = remove_copy( a, b, N );

    for ( size_t i = 0; i < n; i++ ) printf( "%d ", b[i] );
    putchar( '\n' );

    return 0;
}

The program output is

1 2 2 3 3 3 4 4 4 4 5 5 
1 2 3 4 5 

Your code and logic is correct. But you did a mistake by not intializing j = 0. Because of that you were getting some gibberish values. So, I corrected and executed it and got correct answer.

#include <stdio.h>

int main() {
    int arr[12] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5 };
    int temp[12];
    int i, j = 0, k, n = 12;

    for (i = 0; i < n - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            temp[j] = arr[i];
            j++;
        }
    }

    temp[j] = arr[n - 1];

    for (k = 0; k <= j; k++) {
        printf("%d\n", temp[k]);
    }

    return 0;
}
Related