C语言实现一个倒序查找
时间: 2024-04-29 13:24:16 浏览: 10
这里提供两种实现方法:
方法一:利用数组进行倒序查找
```c
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 5; // 要查找的目标值
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
// 从数组末尾开始遍历,查找目标值
for (int i = len - 1; i >= 0; i--)
{
if (arr[i] == target)
{
printf("目标值 %d 在数组中的下标为 %d\n", target, i);
break;
}
}
return 0;
}
```
方法二:利用指针进行倒序查找
```c
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 5; // 要查找的目标值
int len = sizeof(arr) / sizeof(arr[0]); // 数组长度
int *p = arr + len - 1; // 指向数组末尾的指针
// 从数组末尾开始遍历,查找目标值
while (p >= arr)
{
if (*p == target)
{
printf("目标值 %d 在数组中的下标为 %d\n", target, p - arr);
break;
}
p--;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)