用c语言编写两个小程序1、利用选择排序法,从键盘输入8个数,要求按降序排序,输出排序结果。2从键盘输入 20 个字符,统计大写字母出现的次数和小写字母出现的次数。
时间: 2024-11-20 11:39:36 浏览: 12
好的,这里有两个简单的C语言程序示例:
1. **选择排序法降序排列8个数**:
```c
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void selection_sort_descending(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
int max_idx = i;
for (int j = i + 1; j < n; ++j) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
swap(&arr[i], &arr[max_idx]);
}
}
int main() {
int arr[8];
printf("Enter 8 numbers:\n");
for (int i = 0; i < 8; ++i) {
scanf("%d", &arr[i]);
}
selection_sort_descending(arr, 8);
printf("Sorted array in descending order:\n");
for (int i = 0; i < 8; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
2. **统计20个字符的大写字母和小写字母次数**:
```c
#include <stdio.h>
#include <ctype.h>
int count_uppercase(char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; ++i) {
if (isupper(str[i])) {
count++;
}
}
return count;
}
int count_lowercase(char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; ++i) {
if (islower(str[i])) {
count++;
}
}
return count;
}
int main() {
char str[21]; // 为了容纳空字符
printf("Enter 20 characters:\n");
fgets(str, sizeof(str), stdin);
str[strlen(str) - 1] = '\0'; // Remove newline character if present
int uppercase_count = count_uppercase(str);
int lowercase_count = count_lowercase(str);
printf("Uppercase letters: %d\n", uppercase_count);
printf("Lowercase letters: %d\n", lowercase_count);
return 0;
}
```
这两个程序分别实现了选择排序算法用于数字数组的降序排序和字符串字符类型的计数功能。
阅读全文