I can't get this to work? Help...

Okay, so the task I have is simple: I need to write a program that displays all the numbers from 100-1000 that are divisible by 5 AND 6. I also have to make sure that each number is followed by a space and there are only ten numbers per line (this is the part I'm struggling with). Somehow the output for my code always gives me 10 numbers on one line, 11 on the next line, and 9 on the final line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main () {
        int x = 100, i = 1;
        while (x <= 1000) {
                if ((x % 5 == 0) && (x % 6 == 0)) {
                        cout << x << " ";
                        i = i + 1;
                        if (i % 11 == 0)
                                cout << "\n";
                }
                x = x + 1;
        }
        cout << endl;
        return 0;
}


Any help will be much appreciated!
Focus on your IF statement that inserts the line break. What other ways are there to instruct the program to put a line break before the 11th entry?

Also, about the IF statement that determines whether or not the number is divisible by both 5 and 6: it's not incorrect, but there is a more efficient way to phrase it.
@CrashNebula

I'm not sure. Perhaps the while portion itself should express the condition "(x % 5 == 0) && (x % 6 == 0)" to make it more efficient? And as for another way to to output 10 numbers per line, maybe a for loop could be useful? I'm really confused.
Last edited on
Okay, my bad, that was pretty confusing. A for loop would be more efficient,and I do recommend switching, BUT, if you were to stick with what you have now, here's my advice: You said you want the line break after the 10th item, yes? Which is why you decided to set the condition on the if statement to be when i is 11. But 11 is also 10 with a remainder of 1.

The divisible by problem: uh, no, that wouldn't be a good idea. How could you check if a number was divisible by 2 other numbers at the same time? What's the smallest number that's divisible by both 5 and 6? (I'm asking for the actual smallest number here, not within the range you gave). It'd be more efficient for the condition to be that it's divisible by a single number(the smallest number divisible by 5 and 6)
Topic archived. No new replies allowed.