C语言顺序查找算法实现:查找数组元素位置
#include <stdio.h>
int main() { int arr[10]; int x;
// 从键盘输入10个整数,保存到数组中
for (int i = 0; i < 10; i++) {
scanf('%d', &arr[i]);
}
// 输入要查找的整数x
scanf('%d', &x);
// 顺序查找
int index = -1; // 初始化index为-1,表示未查询到
for (int i = 0; i < 10; i++) {
if (arr[i] == x) {
index = i; // 找到x,更新index的值为x在数组中的位置
break; // 查找到了就退出循环
}
}
// 输出结果
if (index == -1) {
printf('Not Found');
} else {
printf('Index is %d', index);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pfvA 著作权归作者所有。请勿转载和采集!