Doubt loop FOR in C

Asked

Viewed 49 times

0

the code’s working as I need it, my doubt is why For didn’t go wrong? For example, if the exponent is 3, it will no longer be greater than 1 and then it would already stop the loop? I was trying to make him for(expoente;expoente<=1;expoente--) and it wasn’t working(this is the way I thought it would make sense). The code is below. It calculates power.

int main()
{

    float pot,base;
    int expoente;
    scanf("%f", &base);
    scanf("%d", &expoente);
    pot=base;

    for(expoente;expoente>1;expoente--)
    {
        pot=pot*base;
    }

    printf("%f", pot);


    return 0;
}
  • It is always good to assign an initial value to the for control variable explicitly, for example: for (exponent=1; exponent<3; exponent++)

2 answers

0

The FOR continues as long as the condition is true, and not the contrary as I think you’re thinking... Note: there are two problems in your code: zero exponent and negative exponent. Good old IF solves easy.... see you.

0

Are you understanding the condition of for on the contrary, as if it were a stopping condition, when in fact it would be "of continuity". That is, the semantics is execute the loop while the expression is true, and come out when it is false.

  • Doubt clarified. Thank you very much!!!

Browser other questions tagged

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