Store positives in one vector and negatives in another

Asked

Viewed 1,651 times

3

Make an algorithm that reads a set of 30 integer numerical values and distributes them between two vectors, separating the positive numbers from the negative ones. Vectors must have 30 positions each. Show vectors at the end of processing.

int vetPos[3], vetNeg[3];
int valor, i, cont;
cont = 1;

do{
    printf("Informe um valor: ");
    scanf("%d",&valor);

    if(valor >= 0){
        //insere no vetor positivo
        for(i=0;i<3;i++){
            vetPos[i] = valor;
        }            
    }else if(valor < 0){
        //insere no vetor negativo
        for(i=0;i<3;i++){
            vetNeg[i] = valor;
        }
    }
    valor = 0;
    cont++;
}while(cont<=3);


//saida de dados
printf("Os números positivos digitados foram: ");
for(i=0;i<3;i++){
    printf("%3d",vetPos[i]);
}
printf("\nOs números negativos digitados foram: ");
for(i=0;i<3;i++){
    printf("%3d",vetNeg[i]);
}

In the do..while I counted up to 3 just for the tests.

In the compiler the result was this:

Tela com o erro

I understand that this error occurs because it needs something like a delimiter for the vector, but I’m not sure if that’s all it is, what can I do?

1 answer

4


It’s much simpler than this:

#include <stdio.h>

int main(void) {
    int pos[3], neg[3], posCount = 0, negCount = 0;
    for (int i = 0; i < 3; i++) {
        int valor;
        printf("Informe um valor: ");
        scanf("%d", &valor);
        if (valor < 0) neg[negCount++] = valor;
        else pos[posCount++] = valor;
    }
    printf("Os números positivos digitados foram: ");
    for (int i = 0; i < posCount; i++) printf("%d ", pos[i]);
    printf("\nOs números negativos digitados foram: ");
    for (int i = 0; i < negCount; i++) printf("%d ", neg[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It makes no sense to have loops to fill the vector, which will cause all positions to have the same value and only the last value entered. It doesn’t make sense to have one either else if when he’s the exact opposite of if. There is too much variable and too few variables to control how many elements were inserted in each vector.

  • Wow, this artificially using the increment within the position variable I couldn’t even imagine, basically it jumps to the next position of the vector only if the position it’s in is filled, this is going to be very useful for other exercises that I had no idea about. Thank you very much.

Browser other questions tagged

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