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

CCBeginner
立即练习

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

简介

在数组中查找最大和最小元素是编程中的一个常见问题。在本实验中,你将学习如何通过逐步的方法编写一个 C 程序来查找数组中的最大和最小元素。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/variables -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} c/data_types -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} c/if_else -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} c/for_loop -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} c/arrays -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} c/user_input -.-> lab-123271{{"`在 C 语言中查找数组中的最大和最小元素`"}} end

声明变量

首先在你的程序中声明必要的变量。我们需要一个整数数组、数组的大小,以及两个整数变量 bigsmall

int a[50], size, i, big, small;

提示用户输入数组元素

接下来,提示用户输入数组的元素。

printf("Enter the size of the array: ");
scanf("%d", &size);

printf("\nEnter %d elements of the array: \n", size);
for(i = 0; i < size; i++)
    scanf("%d", &a[i]);

遍历数组以查找最大元素

现在我们将遍历数组以查找其中的最大元素。

big = a[0]; // 初始化
for(i = 1; i < size; i++)
{
    if(big < a[i])
    {
        big = a[i];
    }
}
printf("The largest element is %d\n", big);

遍历数组以查找最小元素

现在我们将再次遍历数组以查找其中的最小元素。

small = a[0]; // 初始化
for(i = 1; i < size; i++)
{
    if(small > a[i])
    {
        small = a[i];
    }
}
printf("The smallest element is %d\n", small);

编写完整代码

现在你已经看到了各个代码块,让我们将完整代码放在一起。

#include<stdio.h>

int main()
{
    int a[50], size, i, big, small;

    printf("Enter the size of the array: ");
    scanf("%d", &size);

    printf("\nEnter %d elements of the array: \n", size);
    for(i = 0; i < size; i++)
        scanf("%d", &a[i]);

    big = a[0]; // 初始化
    for(i = 1; i < size; i++)
    {
        if(big < a[i])
        {
            big = a[i];
        }
    }
    printf("The largest element is %d\n", big);

    small = a[0]; // 初始化
    for(i = 1; i < size; i++)
    {
        if(small > a[i])
        {
            small = a[i];
        }
    }
    printf("The smallest element is %d\n", small);

    return 0;
}

总结

在本实验中,你学习了如何通过逐步的方法编写一个 C 程序来查找数组中的最大和最小元素。通过理解这些基本的编程概念,你可以继续学习 C 编程中更高级的主题。

您可能感兴趣的其他 C 教程