编写c程序解决下列问题。 1. 计算数组中所有元素的和。 2. 找出数组中元素的最大值和最小值(并找出所在位置)。 3.查找某一个元素是否在数组中。 4.数组元素按照从小到大顺序排列。(雷泡排序、选择
时间: 2024-12-10 18:42:34 浏览: 15
编写C程序来解决上述问题,我们需要分别创建函数来完成每个任务。下面是一些基本的C代码示例:
1. **计算数组元素的和**:
```c
#include <stdio.h>
int sum(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return total;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Array sum is: %d\n", sum(arr, size));
return 0;
}
```
2. **找最大值、最小值及位置**:
```c
#include <stdio.h>
#include <limits.h>
void findMinMax(int arr[], int size, int *min_idx, int *max_idx) {
*min_idx = 0;
*max_idx = 0;
int min_val = INT_MAX, max_val = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] < min_val) {
min_val = arr[i];
*min_idx = i;
}
if (arr[i] > max_val) {
max_val = arr[i];
*max_idx = i;
}
}
}
int main() {
int arr[] = {5, 1, 9, 3, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int min_idx, max_idx;
findMinMax(arr, size, &min_idx, &max_idx);
printf("Minimum value at index %d is %d\n", min_idx, min_val);
printf("Maximum value at index %d is %d\n", max_idx, max_val);
return 0;
}
```
3. **查找元素是否在数组中**:
```c
#include <stdbool.h>
bool searchElement(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return true;
}
}
return false;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
if (searchElement(arr, size, target)) {
printf("%d is present in the array.\n", target);
} else {
printf("%d is not present in the array.\n", target);
}
return 0;
}
```
4. **对数组元素进行冒泡排序(Bubble Sort)**:
```c
#include <stdio.h>
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
以上代码实现了每个功能,你可以根据需要将它们整合到一个更大的项目中。
阅读全文