Search code examples
arrayscfor-loopprintfunique

practicing the basic - problem with program


Im new in this site hope its ok to post question like that. Im trying to learn c language and I got a problem to solve that im stuck with.

-- I need to get 10 number and than print it but with no duplicate number: like if i get 1 2 3 4 5 6 1 2 3 - I need to print only 1 2 3 4 5 6. --

this is what I did:

#include <stdio.h>

int main()
{
    int arr1[10] = {0};
    int arr2[10] = {0};
    int i, j, c;
    
    printf("Please enter 10 numbers:\n");
    
    for (i=0; i<10; ++i) {
        scanf(" %d", &arr1[i]);
    }
    
    i = j = c = 0;
    
    for (i=0; i<10; ++i) {
        while (arr1[i] != arr2[j], j<10) {
            ++j;
        }
         if (j==10) {
               arr2[c] = arr1[i];
               ++c;
            }
        j=0;
    
    }
    
    for (i=0; i<10; ++i) {
        printf("%d ", arr2[i]);
    }
    
   

    return 0;
}

input - 8 1 2 1 2 3 4 5 6 7

output - 8 1 2 1 2 3 4 5 6 7 (I should not print the dupicate numbers)


Solution

  • In this while loop

    while (arr1[i] != arr2[j], j<10) 
    

    there is used an expression with the comma operator. The value of the first operand arr1[i] != arr2[j] of the comma operator is discarded and the result of the expression is the value of the second operand of the comma operator j<10.

    So after the loop the variable j will be always equal to 10. In fact you have the following loop

        while ( j < 10 ) {
            ++j;
        }
    

    because the first operand of the comma operator has no side effect.

    You have to write

    while ( j < c && arr1[i] != arr2[j] ) 
            ++j;
        }
         if (j==c) {
               arr2[c] = arr1[i];
               ++c;
            }
    

    That is there is needed to check only c elements of the second array.

    Also this for loop

    for (i=0; i<10; ++i) {
        printf("%d ", arr2[i]);
    }
    

    should be rewritten like

    for (i=0; i < c; ++i) {
        printf("%d ", arr2[i]);
    }
    

    Actually to output unique elements of an array there is no need to create a second array. The program can look the following way

    #include <stdio.h>
    
    int main( void )
    {
        enum { N = 10 };
        int arr1[N] = {0};
        
        printf( "Please enter %d numbers:\n", N );
        
        for ( size_t i = 0; i < N; ++i ) 
        {
            scanf( "%d", &arr1[i] );
        }
        
        for ( size_t i = 0; i < N; ++i ) 
        {
            size_t j = 0;
    
            while ( j != i && arr1[i] != arr1[j] ) ++j;
    
            if ( j == i ) printf( "%d ", arr1[i] );
        }
    
        putchar( '\n' );
    }
    

    Pay attention to that you should use named constants instead of magic numbers like 10 and you should declare variables in minimum scopes where they are used.