Menu
Coddy logo textTech

Recap - Reversed Array

Part of the Fundamentals section of Coddy's C++ journey. Lesson 64 of 74.

challenge icon

Challenge

Easy

The starter code reads the array size n and then n double numbers into arr. It also declares a second array, reverseArr, and the loop at the end prints reverseArr one element per line.

Your task: fill reverseArr so that it holds the elements of arr in reverse order. Do not change the reading code or the printing loop.

For example, for the input 3, 1, 2, 3 the output is 3, 2, 1 (each on its own line).

One way is to walk arr backwards and copy each element into the next free position of reverseArr. To iterate backwards, start from n - 1 and decrement i:

for (int i = n - 1; i>=0; i--) {...}

Try it yourself

#include <iostream>
#include <vector>

int main() {
    int n;

    std::cin >> n;
    std::cin.ignore();
    double arr[n];

    for (int i = 0; i < n; i++) {
        double val;
        std::cin >> val;
        arr[i] = val;
    }

    double reverseArr[n];
    // Write your code below


    for (int i = 0; i<n; i++) {
        std::cout << reverseArr[i] << std::endl;
    }
    return 0;
}

All lessons in Fundamentals

Practice on your own: Online C++ compiler