Problem with swapping vector positions

Asked

Viewed 1,708 times

-2

Good morning!

Using Dev C++, I am making the following problem in C:

Make a program in C that reads a 20-position vector of the real type. Replace the first position with the 11th, the 2nd with the 12th, the 3rd with the 13th, ..., the 10th with the 20th. the modified vector.

This is my code that’s not working:

#include<stdio.h>
#include<conio.c>

main () {
    float vet[20], aux;
    int i;

    clrscr();

//entrada dos dados
printf("Favor informar 20 valores: ");
for(i=0;i<20;i++) {
    gotoxy(i*3+2,8);
    scanf("%f", &vet[i]);
}
gotoxy(5,20);

//troca dos vetores
for(i=0;i<20;i++) {
    aux=vet[i];
    vet[i]=vet[19-i];
    vet[19-i]=aux;
}

//saida dos dados
gotoxy(2,12);
printf("Vetor modificado: ");
for(i=0;i<20;i++) {
    gotoxy(i*3+2,14);
    printf("%i", vet[i]);
}

getch();
}

I can’t identify the error. What can it be?

  • And what’s the mistake?

  • I am not being able to change the vectors, when compiling the vector exchange they are: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

1 answer

0

The error is in the loop where you exchange the values. You are exchanging the 1° value with the 20°, the 2° with the 19° and so on. The code below does what is requested.

//troca dos valores
for(i=0;i<10;i++) {
    aux=vet[i];
    vet[i]=vet[10+i];
    vet[10+i]=aux;
}

Browser other questions tagged

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