Home > Software engineering >  How do I break out of a loop while creating a string array when the max number of strings allowed is
How do I break out of a loop while creating a string array when the max number of strings allowed is

Time:10-17

I am trying to print a list of friend names entered by the user. The max number of names that can be entered is 5. The user also has option to enter < 5. I don't understand why I am unable to break out of the loop when 5 names have been entered? Thanks

 #include <stdio.h>

 int main(void) {
    
  char namesArray[5][100]; //5 = number of names while 100 = the maximum length of the name

  int x, y;
  char yesNo;
  int counter = 0;

 do {
    for (x = 0; x < 5; x  ) {
    printf("\nEnter a friends name: ");
    scanf(" %s", &namesArray[x][0]);
    counter  ;

    printf("\nWould you like to enter another friends name? Y or N: ");
    scanf(" %c", &yesNo);
    if (yesNo == 'N')
    break;
    }
  } while (yesNo == 'Y' || counter == 5);


 if (yesNo == 'N' || counter == 5){
    for (x = 0; x < counter; x  ) {
    printf("\n\n%s", namesArray[x]);
    }
  }

    return 0;
}

CodePudding user response:

To answer your question:

Your do-while loop never ends because counter is never 5 when the condition is reached. You increase counter inside of the for-loop which ends when x is 5. So counter will be 6 when you leave the first for-loop. (Because when the loop starts x is 0 and you increase counter to 1)

Thus the change to make your code work would be to change the do-while condition to:

 while (yesNo == 'Y' || counter < 5);

The better solution would be to change the code a bit to get rid of the do-while loop entirely. You can just have the for-loop (to make sure a maximum of 5 names will be entered) and add the condition for the yesNo to it so you can break-out before 5 names are entered.

  •  Tags:  
  • c
  • Related