OneBite.Dev - Coding blog in a bite size

Reverse Arrays Items In C++

Code snippet for how to Reverse Arrays Items In C++ with sample and detail explanation

Reverse Arrays Items in C++ is an essential function for any programmer as it maximizes efficiency and outputs a quick result. In C++, arrays hold a series of items, and reversing them is a common task that programmers frequently use.

Code Snippet for Reversing Array Items

The following is a simple code snippet for reversing array items in C++.

#include <iostream>
using namespace std;

int main()
{
   int array[5] = {1, 2, 3, 4, 5};
   int n = sizeof(array) / sizeof(array[0]);

   cout << "Original array: ";
   for (int i=0; i < n; i++)
      cout << array[i] << " ";

   cout << "\nReversed array: ";
   for (int i=n-1; i >= 0; i--)
      cout << array[i] << " ";

   return 0;
}

Code Explanation for Reversing Array Items

The first line of the program is a standard way to include the input and output stream library, i.e., iostream, in your program. The using namespace std; makes the C++ standard libraries accessible.

The main function, int main(), is the function where the program execution begins. Inside it first, we defined an array of five items int array[5] = {1, 2, 3, 4, 5};. We then determined the size n of the array using sizeof(array) / sizeof(array[0]).

Following is a simple loop that iterates over the array from the first index to the last, i.e., from left to right, displaying each item array[i] on the screen. The line cout << "Original array: "; simply prints the original array.

The next loop is a bit different as it starts from the last index and goes to the first index (from right to left), effectively reversing the array. The line cout << "\nReversed array: "; prints the reversed array.

Lastly, the return 0; statement is the “Exit status” of the program. In C++, return 0 indicates successful program termination.

So, that’s a simple way how you can reverse an array in C++. If done correctly, this code will first print the original array and then the reversed array. Try it out and practice until you’ve got the hang of it!

c-plus-plus