用c语言代码实现在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
时间: 2024-05-10 15:17:13 浏览: 17
以下是实现方法:
```c
#include <stdio.h>
#define SIZE 10
int main() {
int arr[SIZE] = {5, 2, 7, 3, 9, 1, 6, 4, 8, 0};
int minIndex = 0;
// 找出最小值的下标
for (int i = 1; i < SIZE; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
// 交换第一个元素和最小值元素的值
int temp = arr[0];
arr[0] = arr[minIndex];
arr[minIndex] = temp;
// 输出交换后的数组
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:
```
0 2 7 3 9 1 6 4 8 5
```
可以看到,最小值元素已经被交换到了数组的第一个位置。
相关问题
用c语言编写在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
下面是用C语言编写的代码实现:
```c
#include <stdio.h>
int main() {
int arr[10] = {5, 8, 2, 9, 1, 7, 4, 6, 3, 0};
int min_index = 0;
// 找出最小元素的下标
for (int i = 1; i < 10; i++) {
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
// 将最小元素与第一个元素对调
int temp = arr[0];
arr[0] = arr[min_index];
arr[min_index] = temp;
// 输出结果
printf("数组排序前:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
运行结果:
```
数组排序前:
0 8 2 9 1 7 4 6 3 5
```
以上代码先利用循环找到一维数组中最小元素的下标,再利用一个临时变量将最小元素与第一个元素对调。最后输出对调后的数组。
使用c语言,在一堆数组中找出值最小的元素,并将数组中的元素按逆序重新存放后输出
可以使用以下代码实现:
```c
#include <stdio.h>
int main() {
int arr[100], n, i, min, temp;
// 读入数组长度和元素
printf("Enter the length of array: ");
scanf("%d", &n);
printf("Enter the elements of array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 找到最小元素
min = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
// 将数组按逆序重新存放
for (i = 0; i < n / 2; i++) {
temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
// 输出结果
printf("The minimum element of array is: %d\n", min);
printf("The array in reverse order is: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
代码先读入数组长度和元素,然后找到数组中的最小元素。接着将数组按逆序重新存放,最后输出结果。
相关推荐
![](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)
![](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)