Exchange of values

The exercise requires to upload a vector of N elements and to exchange the first value with the last one, the second with the second-last etc.
Please, who knows how to do?
Thank you, but the exercise asks to write a code only with for cycle. Who can help me?
Let's see what you have tried, first.
The subroutine is exchange and I think that it works only when "i" (the index) is equal. Can you help to find a solution when the index is odd please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<stdlib.h>
#include<time.h>
#define l_max 6
void carico_t(int[]);
void carico_r(int[]);
void exchange(int[]);
using namespace std;
int main()
{
    int vett[l_max], choice;
    std::cout<<"1) Fill the vector from the keyboard\n";
    std::cout<<"2) Fill the vector with random numbers\n";
    std::cin>>choice;
    switch(choice)
    {
        case(1):
            carico_t(vett);
            break;
        case(2):
            carico_r(vett);
            break;
        default:
            std::cout<<"Errore\n";
    }
    exchange(vett);
    system("PAUSE");
    return 0;
}
void carico_t(int vett[])
{
    std::cout<<"Insert vector elements.\n ";
    for(int i=0; i<l_max; i++)
    {
        std::cin>>vett[i];
    }
}

void carico_r(int vett[])
{
    srand((unsigned int)time(0));
    for(int i=0; i<l_max; i++)
    {
        vett[i]=rand();
    }
}

void exchange(int vett[])
{
    int j=l_max-1, tmp=0;
    for(int i=0; i<(l_max)/2; i++)
    {
        tmp=vett[j];
        vett[j]=vett[i];
        vett[i]=tmp;
        j--;
    }
    std::cout<<"The vector with order reversed is\n";
    for(int i=0; i<l_max; i++)
    {
        std::cout<<vett[i]<<std::endl;
    }
}
As far as i can see your subroutine exchange works fine whether l_max is 6 or 7.

What input do you think gives a problem?
Last edited on
Oh sorry, I’ve just tried and it works fine. Thank you
Topic archived. No new replies allowed.