Function to invert vector c

Asked

Viewed 1,217 times

0

I’m a beginner in c and I’d like to know what’s going wrong with my code. I know I did a trick on the job, but that’s where I got the closest.

#include <stdio.h>

void inverte(int vetor_A[ ], int posicao)
{
    int auxiliar, tamanho_vetor = posicao - 1;

    for (posicao = 0; posicao <= tamanho_vetor; posicao++)
    {
      auxiliar = vetor_A[posicao];
      vetor_A[posicao] = vetor_A[tamanho_vetor];
      vetor_A[tamanho_vetor] = auxiliar;
      tamanho_vetor--;
      printf("%d ", vetor_A[posicao]);
    }
}

int main()
{
    int vetor_A[3], posicao;

    for (posicao = 0; posicao < 3; posicao++)
    {
        printf("Entre com os valores:\n");
        scanf(" %d", &vetor_A[posicao]);
    }

    printf("\n");

    inverte(vetor_A, posicao);

    return 0;
}

He prints it out:

Enter with the values: 3 Enter with the values: 4 Enter with the values: 5
5 4

1 answer

1


Your algorithm is correct. It’s only printing half the vector, because the for within the function inverte only goes through the middle.

You can print after this loop or put in the main function after calling the inverte:

#include <stdio.h>

void inverte(int vetor_A[ ], int posicao)
{
    int auxiliar, tamanho_vetor = posicao - 1;

    for (posicao = 0; posicao <= tamanho_vetor; posicao++)
    {
      auxiliar = vetor_A[posicao];
      vetor_A[posicao] = vetor_A[tamanho_vetor];
      vetor_A[tamanho_vetor] = auxiliar;
      tamanho_vetor--;
    }
}

int main()
{
    int vetor_A[3], posicao;

    for (posicao = 0; posicao < 3; posicao++)
    {
        printf("Entre com os valores:\n");
        scanf(" %d", &vetor_A[posicao]);
    }

    printf("\n");

    inverte(vetor_A, posicao);

    int tamanho = posicao;
    for (posicao = 0; posicao < tamanho; posicao++)
    {
        printf("%d ", vetor_A[posicao]);
    }
    printf("\n");

    return 0;
}
  • So now I understand, I followed your lead and printed it on main. But thinking now, wouldn’t it be wrong to try to print inside the function since it is void type, so not returning anything? I tried to print after the loop on the function and gave the same error as before.

  • Did you store the vector size before the loops? Because in your code after running the first loop inside the inverte the variables posicao and tamanho always end with the value 1 (middle of the vector).

  • Ah, yes. I get it now. Thank you very much.

Browser other questions tagged

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