Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65944208/print-all-elements-in-an-array-just-once-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ( '
' );
    
    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 != ''; ++p )
    {
        const char *prev = s;
        
        while ( prev != p && *prev != *p ) ++prev;
        
        if ( prev == p ) printf( "%c ", *p );
    }
    
    putchar ( '
' );
    
    return 0;
}

The program output is the same as shown above that is

a b c d 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...