Home > Software design >  Problem of modify a for loop program into a while loop program
Problem of modify a for loop program into a while loop program

Time:10-23

I have a problem on changing this program into a while loop and not asking the program for running 4 time, someone told me it will be more reasonable if the program end after found the target name in the array instead of running four times, I have noidea how can I achieve a while loop in this program without running that for 4 time instead of end after match the name in the array. Please help me thanks, I have check it on Google I don't have much idea on it.

For loop code:

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

int main()
{
    char *name[] = {"Peter", "Mary", "John", "Bob", "Kathy"};
    char target_name[10];
    int i, position;

    printf("Enter a name to be searched: ");
    scanf("%s", &target_name);

    position = -1;
    for (i = 0; i <= 4; i  )
        if (strcmp(target_name, name[i]) == 0)
           position = i;

    if (position >= 0)
       printf("%s matches the name at index %d of the array.\n", target_name, position);
    else
       printf("%s is not found in the array.", target_name);

    return 0;
}

While loop code (which someone told me it is more reasonable not running it for 4 times):

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

int main()
{
    char *name[] = {"Peter", "Mary", "John", "Bob", "Kathy"};
    char target_name[10],decision;
    int i, position;

    printf("Enter a name to be searched: ");
    scanf("%s", &target_name);
    i = 0,
    position = -1;
    while ( i <= 4) {
        if (strcmp(target_name, name[i]) == 0)
           position = i;
           i  ;
}
    if (position >= 0)
       printf("%s matches the name at index %d of the array.\n", target_name, position);
    else
       printf("%s is not found in the array.", target_name);

    return 0;

}

CodePudding user response:

you can add break statement to the for loop to be like this:

for (i = 0; i <= 4; i  )
    if (strcmp(target_name, name[i]) == 0) {
        position = i;
        break;
    }

or you can make a while loop with a break also or with a condition like this:

while (position == -1){//do stuff}

so that when you find the element in the array the loop will not be entered again.

  • Related