0
âMultiples of 3â while loop C++
Hi there! I got stuck on this c++ assignment, can not figure out what to do with it. Pretty sure somewhere there must be num%3==0 condition, yet nothing has worked so far. #include <iostream> using namespace std; int main() { //change code int num = 0; while(num<=20){ cout<< num <<endl; num+=1; } return 0; } https://sololearn.com/coach/269/?ref=app
5 Answers
+ 6
Yes, you are right, there should be num % 3 == 0.
This comparison will be your condition on your "if" statement:
For example:
if (num % 3 == ) {
//some code
}
Now it is up to you how you will place this on your code and make it functional. Good luck1
+ 3
I'll just go ahead and assume the task is to print all multiples of three in the range [0, 20], because without PRO I can't see the exercise. If not, ignore this. :)
One possibility would be, like you mentioned, to check if the number is divisible by three in each iteration, by using an if statement, e.g.
if ( num % 3 == 0 )
{
cout << ...
}
However, far simpler and more efficient would be to change the number you increment by. As every third number is divisible by three, and zero is the starting point, adding three in each iteration would guarantee you to go over all numbers divisible by three in the range. This way, you don't need any if branches inside the loop.
0
thank you all, that was super fast and helpful