# Thread: Need help on flip array algorithm

1. ## Need help on flip array algorithm

I have been struggling in finding a way to flip an array.
I want to flip array from begin index to end index.
Code:
```  float  Array[5] = {3.0,  5.7,  6.0,  8.9,  9.4};

this means:  Array[0] = 3.0
Array[1]  = 5.7
Array[2]  = 6.0
Array[3]  = 8.9
Array[4]  = 9.4

How can I flip this array so that it become:

Array[4] = 3.0
Array[3] = 5.7
Array[2] = 6.0
Array[1] = 8.9
Array[0] = 9.4```
If an array is larger such as 1000 elements , how can i flip it by a
special algorithm?

DiepVien_007

2. You could do swapping by introducting a temporary variable.

temp = array [i];
array [i] = array [j];
array [j] = temp;

To swap the complete array you would need to let i run from 0 until half of the array. The variable j runs from the last element index until half of the array. Or, you could calculate j by realising that the j should decrease at same speed as i increases.

3. Hello, well, I don't know if this is a good way to do this, but:
Code:
```#include <stdio.h>

#define SIZE 5

int main(void) {
int i;
float arr[SIZE] = {3.0, 5.7, 6.0, 8.9, 9.4};
float tmp;

for (i=0; i<SIZE; ++i)
printf("arr[%d] = %.1f\n",i,arr[i]);

//rotate the array, loop until the middle (I think)
for (i=0; i<(SIZE/2)+1; i++)
{
tmp = arr[i];
arr[i] = arr[SIZE-i-1];
arr[SIZE-i-1] = tmp;
}

printf("\n\n");
for (i=0; i<SIZE; ++i)
printf("arr[%d] = %.1f\n",i,arr[i]);
return 0;
}```

4. Why do you need to flip it? Why not just process it backwards, like going from index N-1 to 0, instead of 0 to N-1.

5. Simply reversing the array?

Code:
```void Reverse( float array[], int size )
{
int i;
int m = size >> 1;
int j = size - 1;
float temp;

for( i = 0; i < m; ++i, --j )
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}```