Inversion of Array

Asked

Viewed 137 times

1

I want to invert an array, 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 did so only that it is not reversing it just shows the values of the "array" and does not reverse them, how can I solve this problem?

1 answer

3

Reversing was, but you were reversing the impression too. Only changing the side of the variables 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 on IDEONE.

If by chance your compiler isn’t C99 (or you don’t think you can invent a lot of "fashion" in the exercise), take the int of for:

    int i;

    for ( i = 0; i < tamanho; i++ )
  • what does "sizeof(array)" do? what is its function and application?

  • as it is exercise, better not complicate. I put a demo on IDEONE in the answer, if you want to test. But more important than working, is you understand how it was solved. Got the idea? The first version is the same as yours. In the second version, instead of using another variable, we made a simple calculation to go from 5 to zero

  • @Just out of curiosity, an example of the use of sizeof: http://ideone.com/i5AnIr (but for exercise I think it’s best not to invent a lot of fashion) - basically we’re taking the size occupied by the array, and dividing by the size that a float occupies. This returns the number of floats in the array. If you add.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.