Search code examples
c#repeatconsole.writeline

How to repeat a console.writeline x times in c#?


I'm trying to repeat a console.writeline x times (in C#).

The x (type long) is a user input from a console.writeline. So if x is 2, I want 2 console.writelines to follow it. I tried fixing it with Enumerable.Repeat, but that did not work. Also a while loop in which I subtract 1 from x until it is 0 didn't do the trick. Suggestions?


Solution

  • Approach without loops as stated in other comments. Mark as answer if that's fit your needs. Note it has to be int.

    class Program
    {
          static void Main(string[] args)
          {
               string input = Console.ReadLine();
               int d;
               if (int.TryParse(input, out d))
               Console.WriteLine(string.Concat(Enumerable.Repeat("Whatever",d)));
               Console.ReadLine();
          }
    }