用c语言设计一个程序,输出在有$n$ ($n \le 1000$)个元素的顺序表有中采用顺序方法查找关键字 $x$ 的过程。 输入
时间: 2024-05-14 21:19:11 浏览: 51
以下是用C语言实现的程序,可以输出在顺序表中查找关键字x的过程。
```c
#include <stdio.h>
#define MAX_SIZE 1000
int seq_search(int arr[], int n, int x);
int main()
{
int arr[MAX_SIZE];
int n, x, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the value of x to search: ");
scanf("%d", &x);
int index = seq_search(arr, n, x);
if (index == -1)
{
printf("Element not found!\n");
}
else
{
printf("Element found at index %d\n", index);
}
return 0;
}
int seq_search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
{
printf("Checking element %d...\n", i);
if (arr[i] == x)
{
return i;
}
}
return -1;
}
```
输入示例:
```
Enter the number of elements in the array: 5
Enter the elements of the array:
1 4 2 6 8
Enter the value of x to search: 6
```
输出示例:
```
Checking element 0...
Checking element 1...
Checking element 2...
Checking element 3...
Checking element 4...
Element found at index 3
```
阅读全文