Need help with a loop

Jul 6, 2012 at 6:53pm
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]);
Jul 6, 2012 at 6:57pm
So the first pair to be swapped are array[0] and array[x-1].
Jul 6, 2012 at 7:03pm
yes. that is correct.
Jul 6, 2012 at 7:09pm
What do you need help with? You seem to be doing ok.
Jul 6, 2012 at 7:10pm
need help with the loop that will do this. not sure where to start.
Jul 6, 2012 at 7:15pm
You need a swap function or swap statements. For example

int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
Jul 6, 2012 at 7:25pm
what is "tmp"?
Jul 6, 2012 at 9:55pm
It is an intermediate variable that is used for swapping values of array[i] and array[j].
Jul 6, 2012 at 10:02pm
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 
Jul 6, 2012 at 10:06pm
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 Jul 6, 2012 at 10:26pm
Jul 6, 2012 at 11:05pm
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.