Reverse Array

1

I want to invert an array, for example:

void exercicio5()
{
    float array[6] = {10.1, 11.2, 12.3, 127.0, 512.17, -2.5};
    float inverso[6];
    int cont, x = 6;
    for (cont = 0; cont < 6; cont++)
    {
        x--;
        inverso[x] = array[cont];
        printf(" %.2f \n ", inverso[x]);
    }
}

I have done so, so it is not reversing it just shows the array values and does not reverse them, how can I solve this problem?

    
asked by anonymous 04.06.2016 / 01:57

1 answer

3

Reversing was, but you were reversing the impression as well. Just changing the variable side already solves:

void exercicio5()
{
    float array[6] = { 10.1, 11.2, 12.3, 127.0, 512.17, -2.5 };
    float inverso[6];
    int cont, x = 6;
    for (cont = 0; cont < 6; cont++)
    {
        x--;
        inverso[cont] = array[x];
        printf(" %.2f \n ", inverso[cont]);
    }
}

Now, you can simplify it if you want:

void exercicio5()
{
    int   tamanho = 6;
    float array[] = { 10.1, 11.2, 12.3, 127.0, 512.17, -2.5 };
    float inverso[tamanho];

    for ( int i = 0; i < tamanho; i++ )
    {
        inverso[i] = array[tamanho - i - 1];
        printf( "%.2f \n", inverso[i] );
    }
}

See working at IDEONE .

If by chance your compiler is not C99 (or you might as well not invent a lot of "fashions" in the exercise), take out int of for :

    int i;

    for ( i = 0; i < tamanho; i++ )
    
04.06.2016 / 02:11