在数组中查找指定元素c语言
时间: 2023-09-25 12:12:53 浏览: 295
可以使用循环遍历数组,逐个比较数组中的元素是否与指定元素相同,如果找到了相同元素,返回该元素所在位置的索引,否则返回-1表示未找到。
代码示例:
```c
#include <stdio.h>
int findElement(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int index = findElement(arr, n, target);
if (index == -1) {
printf("Element not found.\n");
} else {
printf("Element found at index %d.\n", index);
}
return 0;
}
```
相关问题
在数组中查找指定元素C语言编写函数
可以使用以下C语言代码来编写一个函数来查找一个指定元素在数组中的位置:
```
int findIndex(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
```
在上面的代码中,`arr` 是输入的整数数组,`n` 是数组的长度,`x` 是要查找的元素。函数会遍历整个数组,如果找到了指定元素,就会返回它在数组中的索引。如果没有找到,函数会返回 `-1`。
用c语言写一个在数组中查找指定元素的简单函数
好的,您可以参考以下代码:
```c
#include <stdio.h>
int search(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
int main(void) {
int arr[] = {3, 4, 1, 7, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 7;
int result = search(arr, n, x);
if (result == -1)
printf("%d not found in the array.\n", x);
else
printf("%d is found at index %d.\n", x, result);
return 0;
}
```
这个函数接受三个参数:一个整数数组、数组的长度和要查找的元素。它使用循环遍历数组,如果找到指定元素就返回它在数组中的索引,否则返回-1表示找不到。在main函数中,我们定义了一个整数数组,然后调用search函数来查找7在数组中的位置,并输出结果。