0

Can someone tell me why there is a lot of numbers 4?

Hello! I'm just a beginner who have a little problem, in the line where is "num = 2 * 2, it should give me answer "4", and it did but like 40 times, here is code that i don't understand : #include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { cout << "Number: " << num << endl; num = 2 * 2; } return 0; }

25th Jan 2018, 11:34 AM
Mateusz Borowicz
Mateusz Borowicz - avatar
2 Answers
+ 5
num=2*2 will always give you 4. 4 is lower then 6. As such the loop always repeats.
25th Jan 2018, 11:39 AM
Vlad Serbu
Vlad Serbu - avatar
+ 3
If you want to print 4 as value of num you should put "num = 2 * 2" before making the output. #include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { num = 2 * 2; cout << "Number: " << num << endl; } return 0; } But do you really want to set the value of num constantly to 4? Because with this code the value of num never changes, it is always 4 and the loop has no ending, because num never reaches 6. Maybe this one is better: int main() { int num = 1; while (num < 6) { if (num==4) { cout << "Number: " << num << endl; } num +=1; } return 0; }
25th Jan 2018, 11:46 AM
Jayme
Jayme - avatar