Home > OS >  Print statement after for loop generating an additional iteration
Print statement after for loop generating an additional iteration

Time:03-29

I am very much a beginner in C and was just delving into for loops when I ran into a problem that I solved by winging it and not by understanding. My script adds numbers from 1 to 10 and calculates the average. The thing is that I had to introduce a new variable "number", other than "sum" and "count", to not have the average be wrong.

#include <iostream>
int main ()
{
    float count, sum, avg, number;
    sum=avg=number=0.0;
    for (count=1.0;count<=10.0;count =1.0)
    {
        sum=sum count;
        avg=sum/count;
        number=count;
    }
    printf("\n\nThe number of iterations is %1.f",number);
    printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum);
    avg=sum/number;
    printf("\nThe average is %.1f",avg);
}

Produces the right result, but

#include <iostream>
int main ()
{
    float count, sum, avg;
    sum=avg=0.0;
    for (count=1.0;count<=10.0;count =1.0)
    {
        sum=sum count;
        avg=sum/count;
    }
    printf("\n\nThe number of iterations is %1.f",count);
    printf("\nThe sum of the numbers between 1 and 10 is = %.1f",sum);
    avg=sum/count;
    printf("\nThe average is %.1f",avg);
}   

Gives one more iteration than I expected and causes the average to be wrong. I assume that maybe calling "count" to print adds up but have no certainty and would really like to know why. Sorry if the question but I couldn't figure it out.

CodePudding user response:

In this loop

for (count=1.0;count<=10.0;count =1.0)
{
    sum=sum count;
    avg=sum/count;
    number=count;
}

number can not be greater than 10.0.

But in this loop

for (count=1.0;count<=10.0;count =1.0)
{
    sum=sum count;
    avg=sum/count;
}

count is greater than 10.0 after exiting the loop due to the condition count<=10.0.

So these statements

avg=sum/number;

and

avg=sum/count;

produce different results because number and count are unequal after the loops.

  • Related