Logical error when sorting vector in pair and odd

Asked

Viewed 259 times

0

Well, I was trying to sort a vector in even and odd, that is, half the vector is even and the other odd. It worked "almost" perfectly.

The problem is that the last position always ended up being par. And I could not find the mistake.

From now on, gratitude.

#include <stdio.h>

int main()
{

    int vector[10];
    int aux = 0;

    printf("Digite 10 numeros a serem ordenados em par e impar:\n");

    for (int x = 0; x < 10; x++) {
        scanf("%d", &vector[x]);
    }

    for (int i = 0; i < 10; i++) {
        for (int j = 10; j > 0; j--) {

            if (vector[i] % 2 == 1) {
                aux = vector[i];
                vector[i] = vector[j];
                vector[j] = aux;
            }
        }
    }

    for (int t = 0; t < 10; t++) {
        printf("%d", vector[t]);
    }

    return 0;
}

1 answer

1

Your code was correct, except for one detail in for chained.

#include <stdio.h>

int main()
{

    int vector[10];
    int aux = 0;

    printf("Digite 10 numeros a serem ordenados em par e impar:\n");

    for (int x = 0; x < 10; x++) {
        scanf("%d", &vector[x]);
    }

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {

            if (vector[i] % 2 == 0) {
                aux = vector[i];
                vector[i] = vector[j];
                vector[j] = aux;
            }
        }
    }

    for (int t = 0; t < 10; t++) {
        printf("\n%d", vector[t]);
    }

    return 0;
}

One of them went from 0 to 9 and the inside went from 10 to 1, I also changed the comparison value from 1 to 0, which does not affect much.

  • Excuse me, but what was the mistake in the loop? I have not yet identified kk

  • It was their range, it didn’t cover the whole vector, the last position was out of comparison.

Browser other questions tagged

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