Loop with modulus gives me an error

44 views Asked by At

this is my first time posting a question, but this loop drove me crazy. I cant figure out what is wrong with it. It crashes at the moment when it enters the second loop. It looks fine and makes sense but still it does not work. Any help will be greatly appreciated. Thanks!

/**
Author: Yunus Kulyyev
Date: 10-Dec-2016
Description:
**/

#include <iostream>

using namespace std;

int main()
{
    for (int x=1; x < 10; x++)
    {
        cout << x <<": ";
        for (int y = 0; y <= x; y++)
        {
            if (x%y == 0)
            {
            cout << y;
            }
        }
        cout << endl;
    }

    return 0;
}
1

There are 1 answers

2
Wasi Ahmad On BEST ANSWER

If the second operand of / or % is zero, then the behavior is undefined. See this post in SO. In your program, for the first iteration of the inner for loop, y = 0 and thus the following code snippet results in undefined behavior.

if (x%y == 0) {
    cout << y;
}