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 Final

Chris M
Chris M
592 Points

While loop refuses to acknowledge break command.

Just trying to make it do the command until a value reaches 0. However, it never seems to stop and goes on forever.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {

          Console.Write("Enter the number of times to print \"Yay!\": ");
           // parse the amount of times you want yay printed out
          var ToRpeat = Console.ReadLine();

          // make this all one massive while loop
          while (true)
          {
              // Catching entries that aren't numbers here
           try
            { 
             var total = int.Parse(ToRpeat);
           // while loop starts here


                // Display Yay and then sutract 1 from var 'total'
                Console.WriteLine ("Yay!");
               total -=1;
              if (total == 0)
              {
                break;
              }
            }

          catch(FormatException)
            {
                Console.WriteLine("That is not a valid input.");
                continue;
            }

          }
        }
    }
}

2 Answers

Seth Kroger
Seth Kroger
56,413 Points

Because the line var total = int.Parse(ToRpeat); is inside the loop at the top, your count is always reset at he start of every loop and there is no way for it to reach 0 and break out (unless you enter 1).

Chris M
Chris M
592 Points

Well now I feel incredibly silly! Thanks so much for your help! Works like a charm now.