### Learning loops How do I make multiples of three or five to be printed?

------------------------------------------------------------------------------------------------------
int main()
{
int n;
int sum{ 0 };

cout << "Enter a number: " ;
cin >> n;

while ((sum < n) && ((sum % 3 == 0) || (sum % 5 == 0 )) ){
sum++;
cout << sum << "\n" ;
}

return 0;
}
------------------------------------------------------------------------------------------------------

This code only gives me "1" as the output, but I want all sum divisible by 3 or 5 to print.
e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
Last edited on Close - but the condition for 3 or 5 needs to be within the while loop and not part of it. As it's part of it the loop terminates when the division test fails but you want the loop to continue until all the numbers in range have been tested:

 ``1234567891011121314151617181920`` ``````#include using namespace std; int main() { int n {}; int sum {0}; cout << "Enter a number: "; cin >> n; while (sum < n) { if ((sum % 3 == 0) || (sum % 5 == 0)) cout << sum << ' '; sum++; } return 0; }``````

Note that the code can be simplified:

 ``1234567891011121314`` ``````#include using namespace std; int main() { int n {}; cout << "Enter a number: "; cin >> n; for (int sum {}; sum < n; ++sum) if ((sum % 3 == 0) || (sum % 5 == 0)) cout << sum << ' '; }``````

Last edited on Thank you seeplus!
Topic archived. No new replies allowed.