Value of a "for" returned infinitely

Asked

Viewed 59 times

1

Contextualizing: I have an exercise that suggests creating a program to read student grades and show grades equal or higher than average.

Thus, the following code was written:

#include <stdio.h>

int main(){
    
    float media;
    float alunos[5];
    int posicao;
    float soma=0;
    
    for(posicao=0;posicao<5;posicao=posicao++)
    {
        scanf("%f", &alunos[posicao]);
        soma=soma+alunos[posicao];
    }
    media=soma/5;
    for(posicao=0;posicao<5;posicao++)
    {
        if(alunos[posicao] >= media)
        printf("%.2f \n", alunos[posicao]);
    
    }
    return 0;
}

First doubt: Why when the third parameter of the repeating structure is equal posicao++ it exceeds the limit that should be 5?

Exchanging the value that generated the first doubt for another equivalent posicao=posicao+1, in the construction of the code.

Second question: Why are the notes larger or equal to the average not returned? If typed for example, 1, 2, 3, 4, 5, the sum would be 15 and the average 3, therefore the numbers 3, 4 and 5 should be displayed but are not.

3 answers

3


The first question is that it generates undefined behavior, the compiler can do what he wants with that assignment on top of something that is already an assignment (in this case it is assigning before doing the increment). Hi makes the "manual" assignment or lets the "automatic" increment happen, don’t do both.

It’s just weird to do right one place and wrong the next.

I couldn’t reproduce the second problem, I just rearranged the code and took the error from the first doubt and it worked, as expected.

#include <stdio.h>

int main() {

    float alunos[5];
    float soma = 0;
    for (int i = 0; i < 5; i++) {
        scanf("%f", &alunos[i]);
        soma += alunos[i];
    }
    float media = soma / 5;
    for (int i = 0; i < 5; i++) if (alunos[i] >= media) printf("%.2f\n", alunos[i]);
}

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

  • There is, yeah! Got it. Thanks for the help bro!

0

position++ is a post-increment logo, in position=position++, position is receiving itself and only then being incremented. If it were a preincrement (position=++position), position would be incremented. If the intention is only to increase by 1, just use position++ or ++position, dispensing with the assignment.

0

For C++ code I suggest you replace

    scanf("%f", &alunos[posicao]);

for Cin >> students[position];

and printf("%.2f n", students[i]); for Cout << students[i] << Endl;

Avoid using C or deprecated resources to avoid conflict with more modern compilers

Browser other questions tagged

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