Reverse an Array and Print Its Sum

Beginner

Introduction

In this lab, you will learn how to write a C++ program to read a 1D array, display its elements in the reverse order, and print the sum of the elements.

Create the code file

Create a new code file named main.cpp in the /project directory.

touch ~/project/main.cpp

Include the necessary libraries

In the main.cpp file, include the necessary libraries.

#include <iostream>
using namespace std;

Create the main() function

Create the main() function to read the array, reverse it, and print its sum.

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

Declare variables

Declare the required variables to store the array, its size, and the sum of its elements.

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

Read the size of the array

Read the size of the array from the user.

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

Read the elements of the array

Read the elements of the array from the user.

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

Reverse the array

Reverse the array using a for loop and display its elements in reverse order.

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

Print the sum of the array

Print the sum of all the elements of the array.

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

Compile and run the program

Compile the program using the below command:

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

Full code

Below is the full code of the main.cpp file.

#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;
}

Summary

In this lab, you learned how to write a C++ program to read a 1D array, display its elements in the reverse order, and print the sum of its elements. You also learned how to reverse an array using a for loop and display its elements, and how to calculate the sum of all the elements of the array.

Other Tutorials you may like