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



我有一个问题,把这个程序变成一个while循环,而不是要求程序运行4次,有人告诉我,如果程序在数组中找到目标名称而不是运行四次后结束会更合理,我不知道如何在这个程序中实现一个while循环,而不运行4次,而不是在匹配数组中的名称后结束。请帮助我,谢谢,我在谷歌上查过了,我没有太多的想法。

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}

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

最新更新