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 Final

nave lahav
nave lahav
388 Points

why isn't this working

this code doesn't seem to be the right answer, why is that?

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
         try{
                   Console.Write("Enter the number of times to print \"Yay!\": ");
                var times = Console.ReadLine();
                 int number = Int32.Parse(times);
                     if(number < 0){
                    Console.WriteLine("You must enter a positive number.");


                    }

                int  i = 0;
                while(i != number)
                {

                    i+=1;
                    Console.WriteLine("Yay");

                }

             }
            catch(FormatException)
            {
                Console.Write("You must enter a whole number.");

            }






        }
    }
}

2 Answers

Steven Parker
Steven Parker
216,000 Points

It looks like your loop might run too long.

Looking at your loop condition:

                while(i != number)

That should work for valid inputs, but when the input is negative, the loop would run for very many cycles (nearly infinite). But this case can be easily accomodated by using an inequality test instead: "i < number".

nave lahav
nave lahav
388 Points

can you send an example, I don't quite understand

Steven Parker
Steven Parker
216,000 Points

Just image the number input was -1. As the loop starts "i" is 0, which does not equal -1, so the loop runs. The the next time "i" is 1, which also does not equal -1. Then 2, then 3, etc. Every time through the loop, "i" continues to get bigger, but since it does not equal the number (-1), the loop keeps going.

By testing if "i" is less than tne number instead of just not equal, any negative number will cause the test to fail and the program will end as it should.

Does it make sense now?

try { Console.Write(" Enter the number of times to print \"Yay!\": "); var i = 0; var num = int.Parse(Console.ReadLine()); while(true) { if(i>= num) { break; } Console.WriteLine("Yay!"); i++; } // loop for the number //print Yay! } catch(FormatException) { Console.WriteLine("Error"); }