-1

I Can't just use i < 7 as a general statement for both since the terminal crashes. I want to perform for loop separately for both the statements.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char* name[] = {"Bill", "Charlie", "Fred"};
    char* name2[] = {"George", "Ginny", "Percy", "Ron"};
    
    for (int i=0; i <3; i++) 
            {
            if (strcmp(name[i], "Ron") == 0 || strcmp (name2[i], "Ron") ==0)
             {
                printf("Found\n");
                return 0;
              } 
    }
    printf("Not found\n");
    return 1;
}
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • So you did try ```i < 7``` :-). Why not iterate through the arrays separately? Or combine them into a single array, as they are just names? – Harith Dec 25 '22 at 08:50
  • @Mat But that would just make the code lenghthier. Is there any other way round? – Harshil Zahran Dec 25 '22 at 08:50
  • See also: https://stackoverflow.com/questions/22604196/difference-between-return-1-return-0-return-1-and-exit – Harith Dec 25 '22 at 08:53

1 Answers1

3

How indeed!
You show two separate arrays holding different numbers of elements.
Without arcane calculations attempting to use a single loop counter, the simplest way would be to scan each separately using a function.

#include <stdio.h>
#include <string.h>

int srch( char *name, char **list, size_t lsz ) {
    for( size_t i = 0; i < lsz; i++ ) 
        if( strcmp( name, list[i]) == 0 )
            return 1;
    return 0;
}

int main( void ) {
    char* name[] = {"Bill", "Charlie", "Fred"};
    char* name2[] = {"George", "Ginny", "Percy", "Ron"};
    
    if( srch( "Ron", name,  sizeof name /sizeof name[0]  )
    ||  srch( "Ron", name2, sizeof name2/sizeof name2[0] ) ) {
        printf("Found\n");
        return 0;
    }
    printf("Not found\n");
    return 1;
}

EDIT:
In the spirit of the season, here is an alternative to the above. Note the ease with which a third list can be added to the possibilities.

#include <stdio.h>
#include <string.h>

int srch( const char *name, const char **list, const size_t lsz ) {
    size_t i = 0;
    while( i < lsz && strcmp( name, list[i] ) ) i++;
    return i < lsz;
}

int main( void ) {
    const char* name1[] = { "Dasher", "Dancer", "Prancer", "Vixen", "Comet" };
    const char* name2[] = { "Cupid" };
    const char* name3[] = { "Donner", "Blitzen", "Rudolph" };

    const char *guide = "Rudolph";

    int found =
        srch( guide, name1, sizeof name1/sizeof name1[0] )
    ||  srch( guide, name2, sizeof name2/sizeof name2[0] )
    ||  srch( guide, name3, sizeof name3/sizeof name3[0] )
    ;

    printf( "%sound\n", found ? "F" : "Not F" );

    return !found; // 0 for success; 1 for failure.
}
Fe2O3
  • 6,077
  • 2
  • 4
  • 20