C++: An array from new

Allocate an array whose size comes from the input.

What to build

A program that manages its own heap memory.

Requirements

  • Read n, and allocate an array with new.
  • Read the numbers, print them in reverse order, and print their sum on the next line.
  • Release the memory with delete[].

Input

The first line has n. The second line has n whole numbers.

Output

Two lines.

Constraints

n is from 1 to 1000.

Example

Input:

3
1 2 3

Output:

3 2 1
6

Why it works

The size is known only at run time. delete[] must match new[], so that the whole block is released.

Examples

Example 1 · Input
3
1 2 3
Expected output
3 2 1
6
Example 2 · Input
1
5
Expected output
5
5

Hints

Hint 1

new int[n] gives room for n ints.

Hint 2

Use the pointer like an array.

Hint 3

Finish with delete[].

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int* a = new int[n];
    int sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }
    for (int i = n - 1; i >= 0; i--) {
        cout << a[i] << (i > 0 ? " " : "\n");
    }
    cout << sum << endl;
    delete[] a;
    return 0;
}

Lesson: Pointers and memory →