查找n在数组中最后一次出现的位置
时间: 2024-03-14 08:46:43 浏览: 15
实现这个功能,需要遍历给定的数组并且记录最后一次出现 n 的位置。可以使用一个变量来保存这个位置,每当遍历到一个 n 时,就更新这个变量的值。最后,这个变量的值就是 n 最后一次出现的位置。
以下是一个 C 语言的示例代码:
```c
#include <stdio.h>
int main() {
int arr[] = {3, 5, 2, 1, 5, 4, 3};
int n = 5;
int last_idx = -1;
int size = sizeof(arr) / sizeof(int);
for (int i = 0; i < size; i++) {
if (arr[i] == n) {
last_idx = i;
}
}
if (last_idx == -1) {
printf("%d not found in the array.\n", n);
} else {
printf("%d last appeared at index %d.\n", n, last_idx);
}
return 0;
}
```
在这个示例代码中,我们定义了一个数组 `arr` 和一个整数 `n`,并且使用一个变量 `last_idx` 来记录 n 最后一次出现的位置。遍历数组 `arr`,当遇到 n 时,更新 `last_idx` 的值。最后,根据 `last_idx` 的值输出结果。