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

Daniel Hunter
Daniel Hunter
4,622 Points

I cant work out why this code won't pass this task.

I have no syntax errors and I'm pretty sure the code is doing what the question is asking for but it won't pass the task, also does not give me any more hints as to what I'm doing wrong.

Program.cs
using System;

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

        }
    }
}

1 Answer

Ivan Penchev
Ivan Penchev
13,833 Points

The way this is written is you never "break" out of the while loop. This means you continue to print "yay" until you run out of memory.

         string number = Console.ReadLine();
            int times = int.Parse(number);
            //you need a condition that can be evaluated to "false" sometimes so that you can "break out" of the loop
            while(times > 0)
            {
             //now remove 1, everytime you print "Yay" this way once we reach 0, we can say "break" out of the loop.
                times--;
            Console.WriteLine("Yay!"); 
            }

However a more common way to write this is with a for loop

          Console.Write("Enter the number of times to print \"Yay!\": ");
             //take the number of times you want to print
            var entry = int.Parse(Console.ReadLine());    
            //start from 0 and count up (i++) til you reach your number.
            for (int i = 0; i < entry; i++)
            {
                Console.Write("Yay!");
            }