“Multiples of 3” while loop C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

17th Jan 2021, 4:26 PM
Valerie S
Valerie S - avatar
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
17th Jan 2021, 4:33 PM
noteve
noteve - avatar
+ 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.
17th Jan 2021, 4:36 PM
Shadow
Shadow - avatar
17th Jan 2021, 4:37 PM
Shaishab Chanda
Shaishab Chanda - avatar
0
thank you all, that was super fast and helpful
17th Jan 2021, 6:40 PM
Valerie S
Valerie S - avatar
16th Apr 2021, 6:31 PM
Jonathan Guzik