用c语言写一个在数组中查找指定元素的简单函数
时间: 2023-06-01 10:05:37 浏览: 188
好的,您可以参考以下代码:
```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在数组中的位置,并输出结果。
相关问题
用c语言写一个除去数组中重复元素的函数
以下是用C语言编写一个能够除去数组中重复元素的函数:
```c
void removeDuplicates(int arr[], int n) {
int i, j, k;
for(i = 0; i < n; i++) {
for(j = i + 1; j < n;) {
if(arr[j] == arr[i]) {
for(k = j; k < n; k++) {
arr[k] = arr[k + 1];
}
n--;
}
else {
j++;
}
}
}
}
```
该函数接受一个整数数组和数组的长度作为参数。算法基于双重循环,其中外层循环遍历数组中的每个元素,而内层循环用于查找重复元素并将其删除。如果内层循环找到重复的元素,则将其向左平移一位,并递减数组长度。这样可以确保任何重复的元素均已删除。
您可以通过将此函数与您的主程序结合使用来测试它。例如,您可以使用以下代码:
```c
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
removeDuplicates(arr, n);
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出将是:
```
1 2 3 4 5
```
这显示了在我们的原始数组中除去重复元素的结果。位于输出中的数字表示每个唯一的数字。
在数组中查找指定元素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`。