在 C 语言中查找数组的最大和最小元素

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在数组中查找最大和最小元素是编程中常见的问题,你会经常遇到。这项技能对于各种应用程序都至关重要,例如数据分析、游戏开发和排序算法。

在这个实验中,你将学习如何编写一个 C 程序,用于识别整数数组中的最大和最小元素。我们会将这个过程分解为清晰、易于管理的步骤,帮助你理解这一基本编程技术背后的逻辑。

Finding the largest and smallest elements in an array

这个实验需要你具备 C 编程的基础知识,包括变量、数组、循环和条件语句。在本次实验结束时,你将创建一个完整的 C 程序,展示如何在数据集中查找极值。

设置程序结构

让我们先创建一个新的 C 文件,并设置程序的基本结构。这将包括必要的头文件、主函数和变量声明。

首先,导航到项目目录并创建一个名为 main.c 的新文件:

cd ~/project
touch main.c

现在,在编辑器中打开 main.c 文件并添加以下代码:

#include <stdio.h>

int main() {
    // We'll declare an array with a maximum capacity of 50 elements
    int array[50];
    // Variables to store the size of the array and loop counter
    int size, i;
    // Variables to store the largest and smallest elements
    int largest, smallest;

    printf("Finding Largest and Smallest Elements in an Array\n");
    printf("------------------------------------------------\n\n");

    return 0;
}

这段代码设置了我们程序的基本结构。让我们来了解一下每个部分的作用:

  • #include <stdio.h> 包含标准输入/输出库,该库提供了像 printf()scanf() 这样的函数。
  • main() 函数是我们程序的入口点。
  • 我们声明了一个名为 array 的整数数组,其容量为 50 个元素。
  • size 变量将存储用户想要输入的元素数量。
  • i 变量将用作循环计数器。
  • largestsmallest 变量将存储数组中找到的最大值和最小值。

添加完这段代码后保存文件。这为我们的程序奠定了基础。

获取用户输入

现在我们的程序结构已经准备好,让我们添加代码来获取用户输入。我们需要询问用户数组的大小,然后收集数组元素。

在编辑器中打开 main.c 文件,并在 return 0; 语句之前添加以下代码来修改它:

// Ask user for the size of the array
printf("Enter the size of the array (max 50): ");
scanf("%d", &size);

// Validate the input size
if (size <= 0 || size > 50) {
    printf("Invalid array size. Please enter a size between 1 and 50.\n");
    return 1;
}

// Get array elements from the user
printf("\nEnter %d elements of the array:\n", size);
for (i = 0; i < size; i++) {
    printf("Element %d: ", i + 1);
    scanf("%d", &array[i]);
}

// Display the entered array
printf("\nThe array you entered is: [ ");
for (i = 0; i < size; i++) {
    printf("%d ", array[i]);
}
printf("]\n\n");

这段代码:

  1. 提示用户输入数组的大小。
  2. 验证大小是否在 1 到 50 之间。
  3. 要求用户逐个输入数组的每个元素。
  4. 将输入的数组显示给用户以进行确认。

让我们编译并运行我们的程序,看看目前的情况:

gcc main.c -o main
./main

你应该会看到一个提示,要求输入数组的大小。输入一个较小的数字,如 5,然后输入 5 个值。程序将显示你输入的数组。

例如,如果你输入大小为 5,然后输入值 10、25、5、17 和 9,你应该会看到以下输出:

Finding Largest and Smallest Elements in an Array
------------------------------------------------

Enter the size of the array (max 50): 5

Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9

The array you entered is: [ 10 25 5 17 9 ]

现在我们已经从用户那里收集了数组元素,就可以继续查找最大和最小的值了。

查找最大元素

现在让我们添加代码来查找数组中的最大元素。策略如下:

  1. 假设第一个元素是最大的。
  2. 将后续的每个元素与当前的最大值进行比较。
  3. 如果找到更大的元素,则更新最大值。

main.c 文件的 return 0; 语句之前添加以下代码:

// Initialize largest with the first element of the array
largest = array[0];

// Find the largest element
printf("Finding the largest element...\n");
for (i = 1; i < size; i++) {
    if (array[i] > largest) {
        largest = array[i];
        printf("New largest found at position %d: %d\n", i + 1, largest);
    }
}

printf("\nThe largest element in the array is: %d\n\n", largest);

这段代码将 largest 变量初始化为数组的第一个元素。然后从第二个元素(索引 1)开始遍历数组,将每个元素与当前的最大值进行比较。如果找到更大的元素,就更新 largest 变量并打印一条消息。

让我们编译并运行程序来查看结果:

gcc main.c -o main
./main

像之前一样输入数组的大小和元素。例如,如果你输入的值是 10、25、5、17 和 9,你应该会看到类似于以下的输出:

Finding Largest and Smallest Elements in an Array
------------------------------------------------

Enter the size of the array (max 50): 5

Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9

The array you entered is: [ 10 25 5 17 9 ]

Finding the largest element...
New largest found at position 2: 25

The largest element in the array is: 25

这展示了我们的程序是如何查找数组中的最大元素的。该算法从将第一个元素设为最大值开始,每当找到更大的值时就进行更新。

查找最小元素

既然我们已经找到了最大元素,现在让我们添加代码来查找数组中的最小元素。策略类似:

  1. 假设第一个元素是最小的。
  2. 将后续的每个元素与当前的最小值进行比较。
  3. 如果找到更小的元素,则更新最小值。

main.c 文件的 return 0; 语句之前添加以下代码:

// Initialize smallest with the first element of the array
smallest = array[0];

// Find the smallest element
printf("Finding the smallest element...\n");
for (i = 1; i < size; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
        printf("New smallest found at position %d: %d\n", i + 1, smallest);
    }
}

printf("\nThe smallest element in the array is: %d\n", smallest);

这段代码将 smallest 变量初始化为数组的第一个元素。然后从第二个元素(索引 1)开始遍历数组,将每个元素与当前的最小值进行比较。如果找到更小的元素,就更新 smallest 变量并打印一条消息。

让我们编译并运行程序来查看完整的结果:

gcc main.c -o main
./main

像之前一样输入数组的大小和元素。例如,如果你输入的值是 10、25、5、17 和 9,你应该会看到类似于以下的输出:

Finding Largest and Smallest Elements in an Array
------------------------------------------------

Enter the size of the array (max 50): 5

Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9

The array you entered is: [ 10 25 5 17 9 ]

Finding the largest element...
New largest found at position 2: 25

The largest element in the array is: 25

Finding the smallest element...
New smallest found at position 3: 5

The smallest element in the array is: 5

这展示了我们的程序是如何查找数组中的最大和最小元素的。这两个算法都从第一个元素开始,分别在找到更大或更小的值时进行更新。

优化程序并给出完整代码

现在我们已经有了一个能正常运行的程序,让我们通过将查找最大和最小元素的操作合并到一个循环中来对其进行优化。这样做更高效,因为我们只需遍历数组一次,而不是两次。

打开 main.c 文件,并用以下优化后的版本替换整个内容:

#include <stdio.h>

int main() {
    // We'll declare an array with a maximum capacity of 50 elements
    int array[50];
    // Variables to store the size of the array and loop counter
    int size, i;
    // Variables to store the largest and smallest elements
    int largest, smallest;

    printf("Finding Largest and Smallest Elements in an Array\n");
    printf("------------------------------------------------\n\n");

    // Ask user for the size of the array
    printf("Enter the size of the array (max 50): ");
    scanf("%d", &size);

    // Validate the input size
    if (size <= 0 || size > 50) {
        printf("Invalid array size. Please enter a size between 1 and 50.\n");
        return 1;
    }

    // Get array elements from the user
    printf("\nEnter %d elements of the array:\n", size);
    for (i = 0; i < size; i++) {
        printf("Element %d: ", i + 1);
        scanf("%d", &array[i]);
    }

    // Display the entered array
    printf("\nThe array you entered is: [ ");
    for (i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }
    printf("]\n\n");

    // Initialize largest and smallest with the first element
    largest = smallest = array[0];

    // Find both the largest and smallest elements in a single pass
    printf("Searching for largest and smallest elements...\n");
    for (i = 1; i < size; i++) {
        // Check for largest
        if (array[i] > largest) {
            largest = array[i];
            printf("New largest found at position %d: %d\n", i + 1, largest);
        }

        // Check for smallest
        if (array[i] < smallest) {
            smallest = array[i];
            printf("New smallest found at position %d: %d\n", i + 1, smallest);
        }
    }

    // Display results
    printf("\nResults:\n");
    printf("- The largest element in the array is: %d\n", largest);
    printf("- The smallest element in the array is: %d\n", smallest);

    // Calculate and display the range
    printf("- The range (difference between largest and smallest) is: %d\n", largest - smallest);

    return 0;
}

这个优化后的版本:

  1. 使用一个循环来同时查找最大和最小元素,使程序更高效。
  2. largestsmallest 都初始化为数组的第一个元素。
  3. 增加了对范围(最大值和最小值之间的差值)的计算。

让我们编译并运行优化后的程序:

gcc main.c -o main
./main

像之前一样输入数组的大小和元素。例如,如果你输入的值是 10、25、5、17 和 9,你应该会看到类似于以下的输出:

Finding Largest and Smallest Elements in an Array
------------------------------------------------

Enter the size of the array (max 50): 5

Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9

The array you entered is: [ 10 25 5 17 9 ]

Searching for largest and smallest elements...
New largest found at position 2: 25
New smallest found at position 3: 5

Results:
- The largest element in the array is: 25
- The smallest element in the array is: 5
- The range (difference between largest and smallest) is: 20

这个优化后的版本提供了与之前相同的结果,但更高效,并且包含了关于值范围的额外信息。

在处理大型数组时,这些效率改进可以显著减少计算时间,这在编程中是一个重要的考虑因素。

总结

在这个实验中,你成功创建了一个 C 程序,用于查找数组中的最大和最小元素。让我们回顾一下你学到的内容:

  1. 你搭建了一个包含必要变量声明的基本程序结构。
  2. 你编写了代码来获取用户输入的数组大小和元素。
  3. 你实现了一个算法来查找数组中的最大元素。
  4. 你实现了一个类似的算法来查找数组中的最小元素。
  5. 你通过将两个查找操作合并到一个循环中对程序进行了优化,并添加了额外的功能。

这个实验涵盖了几个基本的编程概念:

  • 数组和数组遍历
  • 使用循环进行迭代
  • 条件语句
  • 算法优化
  • 获取并验证用户输入

这些技能对任何程序员来说都是必不可少的,并且是更复杂的数据结构和算法的基础。在数据集中查找极值是许多编程场景中的常见需求,例如查找游戏中的高分、分析温度读数或处理财务数据。

你可以通过添加以下功能来进一步扩展这个程序:

  • 计算数组所有元素的平均值
  • 对数组进行排序
  • 查找中位数
  • 统计特定值的出现次数

继续练习这些概念,以强化你的编程技能。