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#

Justin Evangelista
Justin Evangelista
7,395 Points

Cleaning up my code

Could anyone help me write this task more efficiently? Thanks!

using System;

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

            try
            {
                var printNum = int.Parse(entry); //Convert entry string to an int named printNum

                if(printNum < 0) //Prompt the user if a positive number is provided
                {
                    Console.Write("You must enter a positive number.");
                }
                else
                {
                    while(printNum > counter) //Print the specified number of "Yay!"s
                    {
                        Console.Write("Yay!");
                        counter++;
                    }
                }
            }
            catch(FormatException)
            {
                Console.WriteLine("You must enter a whole number");
            }

        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,124 Points

This program is a bit simple for effective optimization.

Just meeting the challenge requirements yields an efficient program unless you do something in a very unusual and silly way.

Some of the workspace projects in more advanced courses will be better for practicing optimization on.