Reverse Contents in Array Reverse Contents in Array arrays arrays

Reverse Contents in Array


This would be my approach:

#include <algorithm>#include <iterator>int main(){  const int SIZE = 10;  int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  std::reverse(std::begin(arr), std::end(arr));  ...}


The line

arr[i] = temp;

is wrong. (On the first iteration of your loop it sets arr[i] to an undefined value; further iterations set it to an incorrect value.) If you remove this line, your array should be reversed correctly.

After that, you should move the code which prints the reversed array into a new loop which iterates over the whole list. Your current code only prints the first count/2 elements.

int temp, i;for (i = 0; i < count/2; ++i) {    temp = arr[count-i-1];    arr[count-i-1] = arr[i];    arr[i] = temp;}for (i = 0; i < count; ++i) {    cout << arr[i] << " ";}


I would use the reverse() function from the <algorithm> library.

Run it online: repl.it/@abranhe/Reverse-Array

#include <iostream>#include <algorithm>using namespace std;int main(){  int arr [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  reverse(begin(arr), end(arr));  for(auto item:arr)  {    cout << item << " ";  }}

Output:

10 9 8 7 6 5 4 3 2 1

Hope you like this approach.