### Can someone explain this loop to me?

closed account (4wRjE3v7)
How many times would looping appear in the screen and can someone please explain this thank you.

 ``12345678910111213`` ``````int main() { int num = 5, count = 0; do { cout << "Looping!\n"; num += 5; count++; }while(num < 0); cout << "You looped " << count << " times!\n"; }``````
Last edited on
Do while is a loop that is guaranteed to run atleast once. The condition check is at the end of the loop.
This would loop only once, because as Eddie said, do...while will always loop atleast once, and num is never less than 0 - as a matter of fact, you increment num + 5 every loop so it will loop once, and set num to 10 - and will really solidify the fact that num will never be less than 0

Try this code, instead - Notice that the num variable is initialized with a value of 5, and the while (num <= 20) says run this loop until num = 20; This is achieved by the num += 5 which adds 5 to num every iteration of the loop.
 ``12345678910111213`` ``````int main() { int num = 5, count = 0; do { cout << "Looping!\n"; num += 5; count++; }while(num <= 20); cout << "You looped " << count << " times!\n"; }``````

4 Loops occur because it loops once automatically to test for a condition, then when it see's that num only equals 10, it loops two more times, and then, even though num = 20 by this time, it has to loop one more time before it reaches the conditional that tells it to stop at the bottom, creating 4 loops. - Because it should only loop 3 times right, since num is set to 5 to begin - so add 5, 3 times, after the intial value of 5 and you get 20 - But it has to do that last loop to reach the conditional at the bottom.
Last edited on
closed account (4wRjE3v7)
thanks guys!
Topic archived. No new replies allowed.