Is there any more beautiful way for me to change indexes? [closed]

-5

Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <unistd.h>
#define tam 20

int main (void){
setlocale(LC_CTYPE, "");
    int num[tam];
    int troca[tam];
        for(int i = 0; i < tam; i ++){
            printf("\n\tDigite aqui o %dº número >==> ", i+1);
                scanf("%d", &num[i]);
        }
            for(int i = 0; i < tam; i ++){
            if(i == 10){
                printf("\n");
            }
                troca[0]=num[1];
                troca[2]=num[3];
                troca[4]=num[5];
                troca[6]=num[7];
                troca[8]=num[9];
                troca[10]=num[11];
                troca[12]=num[13];
                troca[14]=num[15];
                troca[16]=num[17];
                troca[18]=num[19];
                troca[19]=num[18];
                troca[17]=num[16];
                troca[15]=num[14];
                troca[13]=num[12];
                troca[11]=num[10];
                troca[9]=num[8];
                troca[7]=num[6];
                troca[5]=num[4];
                troca[3]=num[2];
                troca[1]=num[0];

            sleep(1);

            printf("\t%d", troca[i]);

        }
return 0;
system("pause");
}
    
asked by anonymous 30.06.2017 / 21:35

1 answer

3

How about this?

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <unistd.h>
#define tam 20

int main(void) {
    setlocale(LC_CTYPE, "");
    int num[tam];
    int troca[tam];
    for (int i = 0; i < tam; i++) {
        printf("\n\tDigite aqui o %dº número >==> ", i + 1);
        scanf("%d", &num[i]);
    }
    for (int i = 0; i < tam; i++) {
        if (i == 10) {
            printf("\n");
        }
        for (int j = 0; j < tam; j += 2) {
            troca[j] = num[j + 1];
            troca[j + 1] = num[j];
        }
        sleep(1);
        printf("\t%d", troca[i]);
    }
    system("pause");
    return 0;
}

This makes the exchange in your program more beautiful and more logical. Despite this, I do not understand what the purpose of this program is.

Or better yet, like this:

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <unistd.h>
#define tam 20

int main(void) {
    setlocale(LC_CTYPE, "");
    int num[tam];
    int troca[tam];

    /* Lê todos os números. */
    for (int i = 0; i < tam; i++) {
        printf("\n\tDigite aqui o %dº número >==> ", i + 1);
        scanf("%d", &num[i]);
    }

    /* Realiza as trocas. */
    for (int j = 0; j < tam; j += 2) {
        troca[j] = num[j + 1];
        troca[j + 1] = num[j];
    }

    /* Mostra o resultado. */
    for (int i = 0; i < tam; i++) {
        if (i % 10 == 0) printf("\n");
        printf("\t%d", troca[i]);
    }

    system("pause");
    return 0;
}
    
30.06.2017 / 21:43