Search code examples
cstringfor-loopstrcmp

String Compare issues in C


So the assignment is this: Problem C: Practice Strings (lastnames.c)(8 points)

Read in n, then n lastnames, and check to see if the first in the list is ever repeated again.

Sample Run #1

Enter n, followed by n Last names (each last name must be a single word):

5 Reagan Bush Clinton Bush Obama

First name in list is not repeated.

Sample Run #2

Enter n, followed by n Last names (each last name must be a single word):

4 Bush Clinton Bush Obama

First name in list is repeated.

I can get the first two names to compare, but I can't figure out how to compare the first to whatever is in the second string array. I don't want to post my code in the event that someone searches this and copies mine. I'll send it to you though. Any help would be greatly appreciated.

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

int main(void) 
{   
// initializing character strings
char last[25], first[25];

// initializing number of names, and the index for the number of names
int index, n;

// read in the number
printf("Enter n, followed by n Last names (each last name must be a single word) :\n");
scanf("%d", &n);
scanf("%s", first);

for (index = 0; index < n; index++) 
    scanf("%s", last);

if (strcmp(last, first)== 0)
{
    printf("First name in list is repeated.\n"); 
}
else 
{
    printf("First name in list is not repeated.\n");
}
return 0;
}

Solution

  • #include <stdio.h>
    #include <string.h>
    
    int main(void){
        char last[25], first[25];
        int index, n, repeated = 0;
    
        printf("Enter n, followed by n Last names (each last name must be a single word) :\n");
        scanf("%d", &n);
        scanf("%s", first);
    
        for(index = 1; index < n; index++){ //index = 1 : aleady input first
            scanf("%s", last);
            if(strcmp(last, first)== 0)
                repeated = 1;
        }
        if(repeated)
            printf("First name in list is repeated.\n");
        else 
            printf("First name in list is not repeated.\n");
    
        return 0;
    }