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# question about while loops

Here is a snapshot of what I'm talking about https://w.trhou.se/2upjvfzjfo

I would like to know why the program doesn't exit after the while loop becomes false? If I add an else statement and break out of it then it works fine. Can someone explain this to me?

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi Andrew,

Looking at your code, it will never break out because your code says 'while (true) {}' and true is always true.

You could tweak your code to remove the wrapping 'while' and change the 'if' to 'while' and it should work fine (if you want to use while over a for loop):

using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            int input = int.Parse(Console.ReadLine());

           while (input > 0)
           {
               Console.WriteLine("Yay!");
               input -=1;
           }

        }
    }
}