反转数组

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/operators("`Operators`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123327{{"`反转数组`"}} c/operators -.-> lab-123327{{"`反转数组`"}} c/for_loop -.-> lab-123327{{"`反转数组`"}} c/arrays -.-> lab-123327{{"`反转数组`"}} c/user_input -.-> lab-123327{{"`反转数组`"}} c/output -.-> lab-123327{{"`反转数组`"}} end

声明变量并获取用户输入

在这一步中,我们声明变量并从用户那里获取输入。

#include <stdio.h>

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

    int arr[n];
    printf("Enter %d integers:\n", n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
}

反转数组

在这一步中,我们通过交换数组中的元素来反转数组。循环在到达数组中间时停止。以下是代码块:

for(int i = 0; i < n/2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - i - 1];
        arr[n - i - 1] = temp;
    }

打印反转后的数组

现在我们可以打印反转后的数组。以下代码块可用于打印反转后的数组:

printf("The reversed array is:\n");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

反转数组的完整代码(C 语言):

#include <stdio.h>

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

    int arr[n];
    printf("Enter %d integers:\n", n);

    for(int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    for(int i = 0; i < n/2; i++) {
        int temp = arr[i];
        arr[i] = arr[n - i - 1];
        arr[n - i - 1] = temp;
    }

    printf("The reversed array is:\n");
    for(int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

总结

在 C 语言中反转数组是一项重要的技术。你可以使用本实验中提供的代码来反转任何数组。记住要声明变量、获取用户输入、通过交换元素反转数组,并打印反转后的数组。

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