Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndre Costa
3,559 PointsHello there, why does this loop will execute 1 time?
int =1; do { printf ("looping"); }
while (i<1);
If int i =1, shouldn't it run zero times since "i" will never be less than 1 ?
1 Answer
Stone Preston
42,016 Pointsdo while loops are guaranteed to run at least once. if it were just a regular while loop it would not run at all, however since its a do while loop its guaranteed to run at least once.
what happens is the code in do runs THEN the while condition is tested. if the while condition fails the loop stops after running one time, which is what happens here.
int =1;
//this runs before the condition is checked
do { printf ("looping"); }
//this fails, so the loop exits after running once
while (i<1);
Andre Costa
3,559 PointsAndre Costa
3,559 Pointswhy does it fail? the printf should run and print "looping" shouldn't it?
what is its relation with the integer 1 ? How they are related?
thank you so much
Stone Preston
42,016 PointsStone Preston
42,016 Pointsyes "looping" should get printed one time. it fails because i is 1. the condition in the while clause is i < 1. i is 1, which is not less than one, its equal to it. so the condition fails and the loop exits.