printing reverse of an array in c++ code example

Example 1: reverse an array in c++

#include <iostream>
using namespace std;
int main()
{		// While loop
	const int SIZE = 9;
	int arr [SIZE];
	cout << "Enter numbers: \n";
	for (int i = 0; i < SIZE; i++)
		cin >> arr[i];
	for (int i = 0; i < SIZE; i++)
		cout << arr[i] << "\t";
	cout << endl;
	cout << "Reversed Array:\n";
	int temp, start = 0, end = SIZE-1;
	while (start < end)
	{
		temp = arr[start];
		arr[start] = arr[end];
		arr[end] = temp;
		start++;
		end--;
	}
	for (int i = 0; i < SIZE; i++)
		cout << arr[i] << "\t";
	cout << endl;	
  	return 0;
}

Example 2: printing an array backwards in c++

#include <iostream>
 
// Print contents of an array in reverse order in C++
// using array indices
int main()
{
    int arr[] = { 10, 20, 30, 40 };
    size_t n = sizeof(arr)/sizeof(arr[0]);
 
    // iterate backwards over the elements of an array
    for (int i = n - 1; i >= 0; i--) {
        std::cout << arr[i] << ' ';
    }
 
    return 0;
}

Tags:

C Example