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

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
231,269 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
231,269 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"); }