将for循环程序修改为while循环程序的问题

Problem of modify a for loop program into a while loop program

我在将此程序更改为 while 循环而不询问程序 运行 4 次时遇到问题,有人告诉我,如果程序在找到目标名称后结束会更合理数组而不是 运行 四次,我不知道如何在这个程序中实现 while 循环而不是 运行 4 次而不是在匹配数组中的名称后结束。请帮助我,谢谢,我已经查看了 Google 我对此不太了解。

For循环代码:

#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 循环代码(有人告诉我不是运行 4 次更合理):

#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;

}

你可以像这样在for循环中加入break语句:

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

或者你也可以用一个 break 或者像这样的条件来做一个 while 循环:

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

这样当你在数组中找到元素时就不会再进入循环