c++loopsfor-loopoff-by-one

How to fix off-by-one issue in for-loop


I'm given some variable values which I read from a file and I perform a running total calculation. My goal is to find out how many total calculations I've done. I can get the number right by subtracting 1 from my counter at the end but I would like to not have to do that by changing my condition to better suit it. I realize I'm not using counter in my condition, is that a problem?

Input example: a=10, b=5, t=70

Any help would be appreciated. Tried changing the condition to sum < t instead but it seems to over-calculate past 70.

//Reads and calculates a, b and t, and outputs number of dishes to output.txt
while (inFile >> a)
{       
inFile >> b >> t;

for (counter = 0; sum <= t ; counter++)
{
sum += a + (counter * b);
}
outFile << " " << a << "\t\t" << b << "\t\t" << t << "\t\t" << counter -1 << endl; //Output iteration results

//Reset total before next iteration
sum = 0;
}

Solution

  • Something like this. It uses a temp variable which is the next value of sum and aborts the loop if that value is too large.

    for (counter = 0; ; ++counter)
    {
        int temp = sum + a + (counter * b);
        if (temp > t)
            break; // too big quit the loop
        sum = temp;
    }
    

    Now counter and sum should have the correct values at the end of your loop.