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.

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

Isaac Lau
Isaac Lau
3,767 Points

Don't understand the Quiz

the question :

int counter = 0;

while(counter < 5)
{    
    counter += 1;

    if(counter == 2)
    {
        break;
    }
}

Console.WriteLine(counter);

i want to double confirm What's mean (Counter ==2)? And the answer should be counter = 1?

thank you

1 Answer

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Issac,

The counter variable will have a value of 2 after the while loop. Let's see why.

Counter starts at 0, so the first iteration of the loop will increment counter to 1 and the if condition will be false, so the loop continues to the next iteration.

Next iteration, the counter is incremented again, making the counter 2. Immediately after counter is incremented, the if condition is true and the while loop is exited. The result: the value of counter is 2.

I hope this helps.

Happy Coding :)