At the last run of the repeat loop the entered value is assigned to my counter

Asked

Viewed 54 times

1

I put a printf() to track what happened and everything was normal, until I type my last value and it is assigned to the counter quantN. The conditional even works when it is a negative value, it adds one more to the value (-5 turns -4).

#include <stdio.h>

int main(){
    int i = 0, somaP = 0, quantN = 0, valores[9];

    for (i = 0; i <= 9; i++){
        printf("Digite o %do valor: ", i + 1);
        scanf("%d", &valores[i]);
            if(valores[i] < 0){
                quantN++;
            } else {
                somaP += valores[i];
            }     
    }

    printf("Soma dos positivos: %d\n", somaP);
    printf("Quantidade de negativos: %d\n", quantN);

    system("pause");
}

1 answer

2


The main problem is that you are asking for 10 values but are reserving space only for 9 in array.

Of course there is also no validation of the typed data so strange things can happen in the execution, but this will not bring problem if everything is typed right. I didn’t see the need to have one array then, if you had done it in a simple way, the error would not even happen (unless the exercise asks you to print all the values typed after).

I took the opportunity to make the condition of for in a more natural way for programmers and modernized some things.

#include <stdio.h>

int main() {
    int somaP = 0, quantN = 0, valores[10];
    for (int i = 0; i < 10; i++) {
        printf("Digite o %do valor: ", i + 1);
        scanf("%d", &valores[i]);
        if (valores[i] < 0) quantN++;
        else somaP += valores[i];
    }
    printf("\nSoma dos positivos: %d\n", somaP);
    printf("Quantidade de negativos: %d\n", quantN);
}

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

  • As the array starts at position 0 ended up confusing me, now I understand how it works. And I used array because the exercise list was designed to practice it, so I didn’t even stop to ask questions. Thank you so much for answering the question and introducing me to the edited code, I will start using this pattern.

Browser other questions tagged

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