For my computer lab class we were given a program with an infinite loop, and I am unsure what to do. Here is the program.

#include <iostream>
#include <string>
using namespace std;

int main() {

        int Total;        // running sum of the fraction total
        int n;            // number of fraction units
        int Fraction;     // will be 1/n;
        int LoopCounter;  // number of times for loop has executed so far
        n = 2;
        Fraction = 1/n;
        LoopCounter = 0;
        for (Total = 0; Total != 1; Total += Fraction) {
                ++LoopCounter;
        }
        cout << "The total is " << Total << "\n" ;
        return 0;

Can someone help me with the terminating factor??

Edited 3 Years Ago by happygeek: fixed formatting

>I dont really know what that is supposed to mean. Help?

If Fraction is zero, your loop increment is adding zero to Total. How is Total supposed to ever be anything other that what it was when the loop started?

That code isn't an infinite loop. It loops twice adding 1/2 each time round ending up with a total of 1.

The following would "in theory" be an infinite loop but in practice would terminate once the fractions became too small for the computer to track properly.

#include <iostream>
#include <string>
using namespace std;

int main() {

int Total; // running sum of the fraction total
int n; // number of fraction units
int Fraction; // will be 1/n;
int LoopCounter; // number of times for loop has executed so far
n = 2;
Fraction = 1/n;
LoopCounter = 0;
for (Total = 0; Total != 1; Total += Fraction) {
Fraction /= n;
++LoopCounter;
}
cout << "The total is " << Total << "\n" ;
return 0;

Your right, I missed the int when working out how the loop works. Divide 1 by 2 in integer maths and you'd have to get either 1 or 0 returned depending on how the code is evaluated so it either doesn't loop at all or loops forever.

This article has been dead for over six months. Start a new discussion instead.