Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Contents in Array

I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.

The output reads: 10 9 8 7 6. Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10

void reverse(int [], int);

int main ()
{
   const int SIZE = 10;
   int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   reverse(arr, SIZE);
   return 0;
}
void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      arr[i] = temp;
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;

      cout << temp << " ";
   }
}
like image 972
John Avatar asked Oct 31 '13 17:10

John


People also ask

What is array order reversal?

The JavaScript array reverse() method changes the sequence of elements of the given array and returns the reverse sequence. In other words, the arrays last element becomes first and the first element becomes the last. This method also made the changes in the original array.

How will you reverse the array names?

JavaScript Array reverse() The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.


1 Answers

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));
  ...
}
like image 178
juanchopanza Avatar answered Nov 02 '22 00:11

juanchopanza