#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = n - 1; i >= 0; i--) {
cout << arr[i] << " ";
}
return 0;
}
Let's break down the code and explain each part:
#include
using namespace std;: This statement allows us to use the standard library functions without explicitly specifying the namespace (e.g., cout, cin).
int main() { ... }: This is the main function of the program. It is the entry point for execution.
int n; cin >> n;: We declare an integer variable n to store the size of the array. The user is prompted to enter the value of n using cin.
int arr[n];: We declare an integer array arr of size n using the variable n as the size. Note that in modern C++, variable-length arrays (VLAs) like arr[n] are supported, but they are not part of the standard C++ language. However, some compilers provide this feature as an extension.
for (int i = 0; i < n; i++) { ... }: This for loop is used to iterate over the array indices from 0 to n-1. Inside the loop, the user is prompted to enter the values for each element of the array using cin >> arr[i].
for (int i = n - 1; i >= 0; i--) { ... }: This for loop is used to iterate over the array indices in reverse order, starting from n-1 and going down to 0. Inside the loop, each element of the array is printed in reverse order using cout << arr[i] << " ";. The space after arr[i] ensures that the elements are separated by a space.
return 0;: This line indicates that the program execution is successful and returns the value 0 to the operating system.
When you run this program, it will prompt the user to enter the size of the array (n). Then, it will ask the user to enter n values, which will be stored in the array arr. Finally, it will print the elements of the array in reverse order, separated by spaces.
To use this code in HackerRank's "Arrays Introduction" problem, you can copy and paste it into the editor and submit it. The program will prompt the user for input, and the output will be displayed in the output window or terminal, depending on the HackerRank environment.
Make sure to read the problem statement and input/output requirements carefully and adjust the code accordingly if needed.