Search code examples
carraysstrcpy

finding the min string in an array of chars


I'm trying to find the MIN string out of a bunch of strings in a 2D array initialized with empty strings "". The user enters some strings which are then strcpyied and then the following method gets called.However the if statement doesn't work as expected:

void determineMIN(char strings[][MAX]) {
  char minC[MAX] = "Z"; // Highest alphabetic uppercase char in ASCII(value: 090)
  int i;
  for(i=0; i < MAX; i++) {
    if((strcmp(minC,strings[i]) >= 0) && (strcmp(minC,"") != 0)) { 
      printf("called\n");
      strcpy(minC,strings[i]);
    } else { // < 0
      continue;
    }
  }
  printf("MIN: %s\n",minC);
}

Take this case for example: the user enters the following 3 strings "cat","dog" and "sheep" .Considering the rest of the array is filled with "" strings shouldn't my condition work? Because it doesn't it only gets called once and then minimum is set to "".


Solution

  • Your problem is that you skip if minC is equal to "", but you should check strings[i]:

    void determineMIN(char strings[][MAX])
    {
      char minC[MAX];
      int i;
    
      strcpy(minC, strings[0]);
      for(i=1; i < MAX; i++)
      {
        if((strcmp(strings[i],"") != 0) && (strcmp(strings[i], minC) < 0)) 
        { 
          printf("called\n");
          strcpy(minC,strings[i]);
        }
        else
        {
          continue;
        }
      }
      printf("MIN: %s\n",minC);
    }