Need help with a loop

I need help with a loop that will take and array and exchange the outermost pair of numbers, then the next pair of numbers,etc.

basically need it to take an array (say: 1,2,3,4,5,6) and then output something like this:

array after exchange: (6,5,4,3,2,1)

here's what i have so far, just not sure how to do the loop.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iostream.h>
using namespace std;

int main ()
{
    int array[] = { 1, 2, 3, 4, 5, 6};
    int x;
    
    x = sizeof(array) / sizeof(array[0]);
So the first pair to be swapped are array[0] and array[x-1].
yes. that is correct.
What do you need help with? You seem to be doing ok.
need help with the loop that will do this. not sure where to start.
You need a swap function or swap statements. For example

int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
what is "tmp"?
It is an intermediate variable that is used for swapping values of array[i] and array[j].
need help with the loop that will do this. not sure where to start.
You need to swap all elements, and as you're handling two elements at a time, you need to loop at least x/2 times.

So you need a loop that goes around x/2 times. Something like:
1
2
for (i = 0; i < x/2; ++i)
    // swap elements 
OK. here's what I have, am I on the right track?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iostream.h>
using namespace std;

int main ()
{
    int array[] = { 1, 2, 3, 4, 5, 6};
    int x;
    
   int array[]= {};
    int y;
    
    x = sizeof(array) / sizeof(array{0});
    
    for (i = 0; i < x/2; ++i)
    
    int tmp = array[x];
    array[x] = array[y];
    array[y] = int tmp;
Last edited on
The syntax is off, you've declared array twice and you've introduced y without assigning it a value, but it seems headed in the right direction.

I'm not sure if you're struggling with the C++ syntax or genuine problems with the algorithm.
Topic archived. No new replies allowed.