#include <stdio.h>
int main() {
int i, n, arr[8];
// Input 8 integer elements into the array
printf("Enter 8 integer elements:\n");
for(i = 0; i < 8; i++) {
scanf("%d", &arr[i]);
}
// Input an integer to search for
printf("Enter an integer to search for: ");
scanf("%d", &n);
// Search for the integer in the array
int index = -1;
for(i = 0; i < 8; i++) {
if(arr[i] == n) {
index = i;
break;
}
}
// Output the result
if(index != -1) {
printf("%d is found at index %d in the array.\n", n, index);
} else {
printf("%d no found \n", n);
}
return 0;
}
代码核心思想,因为当我们找到该元素时我们要输出的是该元素数组的下标,所以我们需要用到一个变量index来存储。当找到时要用到break来跳出这个for循环因为index的初值为-1。当index不为-1时说明找到了。
标签:index,arr,int,整数,数组,printf,integer,array,输入 From: https://blog.csdn.net/m0_73864454/article/details/136708665