I. Experimental purpose and experimental requirements
(1) In-depth understanding of how one-dimensional and two-dimensional arrays are organized in memory.
(2) Proficient in the definition, initialization and access methods of one-dimensional array and two-dimensional array elements.
(3) Proficient in general sorting algorithms, such as bubble sorting, selection sorting and so on.
2. Experimental content
1, there are 30 students in a class, after the C language midterm exam, the teacher wants you to write a program to achieve the following functions:
(1) Input the scores of n students from the keyboard; (n input by user keyboard)
(2) Calculate the average scores of n students and output them;
(3) Find the highest score and the lowest score, and output; (Cannot use sorting algorithm)
(4) The grades of n students are sorted in descending order (bubble sorting method and selection sorting method can be used), and output.
#include <stdio.h>
int main() {
int i, j, t, max, min, n, a[30], sum = 0;
float average;
printf("请输入学生人数(最多30人):");
scanf("%d", &n);
printf("请输入%d个学生成绩:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
average = (float)sum / n;
printf("学生成绩的平均分为:%.2f\n", average);
min = max = a[0];
for (i = 1; i < n; i++) {
if (max < a[i])
max = a[i];
if (min > a[i])
min = a[i];
}
printf("最高分为:%d,最低分为:%d\n", max, min);
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (a[j] > a[min])
min = j;
}
if (min != i) {
t = a[i];
a[i] = a[min];
a[min] = t;
}
}
printf("学生成绩的降序排序为:");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
2, define the two-dimensional array int array[4][4], input integers from the keyboard to the array array assigned value. Request:
(1) The sum of sub-diagonal elements of array;
(2) array The sum of elements whose row and column subscripts are all even (loop implementation).
#include <stdio.h>
#include <string.h>
#pragma warning(disable : 4996) // 禁用警告 C4996
void main()
{
int array[4][4], i, j;
int x = 0, y = 0;
printf("请输入二维数组的元素:\n");
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
scanf_s("%d", &array[i][j]); // 使用 scanf_s 替换 scanf
}
}
for (i = 0; i < 4; i++)
x += array[i][3 - i];
printf("数组的次对角线元素之和为:%d\n", x);
for (i = 0; i < 4; i += 2)
{
for (j = 0; j < 4; j += 2)
{
y += array[i][j];
}
}
printf("数组中行、列下标均为偶数的元素之和为:%d\n", y);
}