Search code examples
arrayscloopsprintfunique

Print all elements in an array just once in C?


I have created an array in C and I know how to print every element in an array but couldn't figure it out how to not print repeated elements, or to be more precise, like I ask in the title, how can I print all elements just once?

For example my array is: [a b c d a a b d c c]

I want to print it like this: [a b c d]

I think that I should use for or while loop, but I don't know how. I have been thinking about this for hours and did some research but couldn't find anything valuable.


Solution

  • Here you are.

    #include <stdio.h>
    
    int main(void) 
    {
        char a[] = { 'a', 'b', 'c', 'd', 'a', 'a', 'b', 'd', 'c', 'c' };
        const size_t N = sizeof( a ) / sizeof( *a );
        
        for ( size_t i = 0; i < N; i++ )
        {
            size_t j = 0;
            
            while ( j != i && a[j] != a[i] ) ++j;
            
            if ( j == i ) printf( "%c ", a[i] );
        }
        
        putchar ( '\n' );
        
        return 0;
    }
    

    The program output is

    a b c d 
    

    Or for example if you have a character array that contains a string then the same approach can be implemented the following way.

    #include <stdio.h>
    
    int main(void) 
    {
        char s[] = { "abcdaabdcc" };
    
        for (const char *p = s; *p != '\0'; ++p )
        {
            const char *prev = s;
            
            while ( prev != p && *prev != *p ) ++prev;
            
            if ( prev == p ) printf( "%c ", *p );
        }
        
        putchar ( '\n' );
        
        return 0;
    }
    

    The program output is the same as shown above that is

    a b c d