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 trialjack Sandberg
1,659 PointsI don't understand why it print "Yay" one extra time.
How come it print yay one extra time? When I print 5 it print "yay" 6 times instead if 5 . Is it because the incrementing I in the for loop ? if so how do i fix it ? I dont really understand what the problem is.
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
bool onGooing = true;
if (onGooing)
{
Console.Write("Enter the number of times to print \"Yay!\": ");
String userInput = Console.ReadLine();/*Get user input */
int counter = 0; /* count how many time the loop has run */
int Input = 0;
try
{
Input = int.Parse(userInput);/*try it input is an int, if not catch*/
}
catch (FormatException)
{
Console.WriteLine("Your input is invalid try again"); /* if the input is everything els than an int*/
}
if (Input > 0)
{
for (int i = 0; i <= Input; i ++)
{
Console.WriteLine("Yay");
counter++;
continue;
}
}
else if (Input <0) {
Console.WriteLine("Invalid input,you have to input a bigge number then 0");
}
}
/*hรคr avslutas koden*/
}
}
}
1 Answer
Meelis Talvis
2,007 PointsYou are correct. Your mistake is in the for loop.
for (int i = 0; i <= Input; i ++)
Since i = 0 then in case of Input = 5, you actually run the loop 6 times since your logical comparison is <=. If you change it to be just less than (<) then you would print out Yay the correct amount of times.
jack Sandberg
1,659 Pointsjack Sandberg
1,659 PointsThanks you so much!