反转数组并打印其元素之和

C++C++Beginner
立即练习

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

介绍

在本实验中,你将学习如何编写一个 C++ 程序来读取一维数组,以相反的顺序显示其元素,并打印元素的总和。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/arrays("`Arrays`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/StandardLibraryGroup -.-> cpp/math("`Math`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/data_types -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/arrays -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/for_loop -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/output -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/user_input -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/files -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/math -.-> lab-96212{{"`反转数组并打印其元素之和`"}} cpp/code_formatting -.-> lab-96212{{"`反转数组并打印其元素之和`"}} end

创建代码文件

/project 目录下创建一个名为 main.cpp 的新代码文件。

touch ~/project/main.cpp

包含必要的库

main.cpp 文件中,包含必要的库。

#include <iostream>
using namespace std;

创建 main() 函数

创建 main() 函数以读取数组、反转数组并打印其元素之和。

int main()
{
    // Write code here
    return 0;
}

声明变量

声明所需的变量以存储数组、数组大小及其元素之和。

int arr[100], size, sum = 0;

读取数组大小

从用户输入中读取数组的大小。

cout << "Enter the size of the array: ";
cin >> size;

读取数组元素

从用户输入中读取数组的元素。

cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++) {
    cin >> arr[i];
}

反转数组

使用 for 循环反转数组,并以相反的顺序显示其元素。

cout << "The reversed array is: ";
for (int i = size - 1; i >= 0; i--) {
    cout << arr[i] << " ";
    sum += arr[i];
}
cout << endl;

打印数组元素之和

打印数组中所有元素的和。

cout << "The sum of the array is: " << sum << endl;

编译并运行程序

使用以下命令编译程序:

g++ main.cpp -o main && ./main

完整代码

以下是 main.cpp 文件的完整代码。

#include <iostream>
using namespace std;

int main()
{
    int arr[100], size, sum = 0;

    cout << "Enter the size of the array: ";
    cin >> size;

    cout << "Enter the elements of the array: ";
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }

    cout << "The reversed array is: ";
    for (int i = size - 1; i >= 0; i--) {
        cout << arr[i] << " ";
        sum += arr[i];
    }
    cout << endl;

    cout << "The sum of the array is: " << sum << endl;

    return 0;
}

总结

在本实验中,你学习了如何编写一个 C++ 程序来读取一维数组、以相反顺序显示其元素并打印其元素之和。你还学习了如何使用 for 循环反转数组并显示其元素,以及如何计算数组中所有元素的和。

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