Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Objective-C Basics (Retired) Functional Programming in C Loops

Andre Costa
Andre Costa
3,559 Points

Hello 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
Stone Preston
42,016 Points

do 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
Andre Costa
3,559 Points

why 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
Stone Preston
42,016 Points

yes "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.