Invert array (positions)

2

I am trying to make an inversion of an array in the C language.

For example: I have an array [1, 2, 3] , I need to invert the numbers in the SAME array, giving an output like this: [3,2,1] . I'm trying, but on reaching the second position of the array, it starts to mirror. Here is the code and thank you right away:

int main(int argc, char** argv) {
    int x[4];
    int i, j, aux;

    for (i = 0; i <= 3; i++){
        printf("\nEscreva um numero\n");
        scanf("\n%d", & x[i]);  
    }

    i = 0;
    for (j = 3; j >= 0; j = j - 1){
        aux = x[i];
        x[i] = x[j];
        x[j] = aux;

        i++;
    }

    for (i = 0; i <= 3; i++){
        printf("\n numero: %d\n", x[i]);    
    }       
}
    
asked by anonymous 07.12.2016 / 20:09

2 answers

4

The answer to the question comes down to a line:

You can not get past the half of the vector in your loop, otherwise you are flipping and "flushing" again as you pass the middle.


Just as an add-on, follow code:

Forget the z and do it right on x

for (j = tamanho-1; j > (tamanho/2); j = j - 1){
    aux = x[i];
    x[i] = x[j];
    x[i] = aux;        
    i++;
}

See working at IDEONE .

If you want to optimize a bit (and make the size more flexible), here's another example:

int main(int argc, char** argv) {
    int x[7];
    int i, aux;
    int tamanho = sizeof(x)/sizeof(int);

    for (i = 0; i < tamanho; i++){
        printf("\nEscreva um numero\n");
        scanf("\n%d", & x[i]);  
    }

    for (i = 0; i <= (tamanho/2); i++){
        aux = x[i];
        x[i] = x[tamanho-i-1];
        x[tamanho-i-1] = aux;
    }

    for (i = 0; i < tamanho; i++){
        printf("numero: %d\n", x[i]);    
    }
}

Also working on IDEONE .

Note that Daniel Grillo's response (which has already received my +1) also has an elegant solution, which is to check the loop by comparing j with i , and could be optimized for for (j = 3; j > i; j--){

    
07.12.2016 / 20:47
2

Try this:

i = 0;
for (j = 3; j >= i; j--){
    aux = x[j]; 
    x[j] = x[i];
    x[i] = aux;
    i++;    
}
    
07.12.2016 / 20:59