0

I've written some code but the while loop doesn't exit?

#include <iostream>

#define TriangleNumber(x) (x * (x + 1)) / 2

int main(int argc, char* argv[])
{
    int idx       = 0;
    int n_factors = 0;
    int triangle_num = 0;
    while (n_factors < 3)
    {
        int n_factors    = 0;
        triangle_num = TriangleNumber(idx);
        for (int i = 1; i <= triangle_num; i++)
        {
            if (triangle_num % i == 0)
            {
                n_factors++;
            }
        }
        idx++;
    }
    std::cout << "Number with greater than 3 factors = " << triangle_num;
    return 0;
}

Expect to exit at idx = 3 and triangle number 6.

2 Answers2

3

You re-declared the exact same variable name twice, so the n_factors++ is referring to the one inside the inner loop. Remove int from the inner loop, and your program will output

Number with greater than 3 factors = 6

Working code:

#include <iostream>

#define TriangleNumber(x) (x * (x + 1)) / 2

int main(int argc, char* argv[])
{
    int idx       = 0;
    int n_factors = 0;
    int triangle_num = 0;
    while (n_factors < 3)
    {
        n_factors    = 0;
        triangle_num = TriangleNumber(idx);
        for (int i = 1; i <= triangle_num; i++)
        {
            if (triangle_num % i == 0)
            {
                n_factors++;
            }
        }
        idx++;
    }
    std::cout << "Number with greater than 3 factors = " << triangle_num;
    return 0;
}
Water
  • 3,245
  • 3
  • 28
  • 58
1

You are redefining n_factors twice, outside and inside the while loop. The one you are incrementing is the one inside the loop while the one that the loop checks against is the outsider, which is always zero in your case i.e always less than 3.

Islam Hassan
  • 673
  • 1
  • 10
  • 21