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 trial

C# C# Basics (Retired) Perfect break and continue

Grigor Samvelian
Grigor Samvelian
2,852 Points

Could someone please explain to me why the answer is 2?

int counter = 0;

while(counter < 5) { counter +=1; if(counter == 2) { break; } }

Question is asking what will be printed out, don't fully understand why the answer is 2. Thank you!

3 Answers

Jake Kobs
Jake Kobs
9,215 Points

It all has to do with the counter variable. Through every iteration of the loop, the counter variable increments by one and tests the condition of if(counter == 2) and while(counter < 5). Once it reaches 2, the code breaks out of the loop. The code doesn't get all the way to 4 because the if statement breaks the loop. The "==" is the comparison operator to see if two values are the same, but don't get double equals mixed up with "=", as that's for setting values. Hope this helps!

Grigor Samvelian
Grigor Samvelian
2,852 Points

Crystal clear now Jake, Appreciate your response!

Allan Clark
Allan Clark
10,810 Points

Think about how the execution will behave when the code is run, in more of plain english steps the code reads like this:

create 'counter' variable and set it to 0

loop through the while block while 'counter' is less than 5

the loop increments the counter

after the increment, check if 'counter' is equal to 2, if so break out of the loop

print counter after loop

Like this it should become clear that no matter what counter is, it will only ever break out of the loop to get to the WriteLine statement when counter == 2.

Hope this helps! Happy coding!

Grigor Samvelian
Grigor Samvelian
2,852 Points

makes perfect sense now! Appreciate it Allan, Happy coding!

Tsenko Aleksiev
Tsenko Aleksiev
3,819 Points

Is counter = 5? No, keep updating the counter aka +1, is counter = 5 ( is 1 = 5 ), no keep updating counter aka +1, now counter is equal to 2. Here you have a second condition: if counter is equal to 2, well yea it is, than break aka stop and get out of the while loop :) That is it