How to print 1 to 100 without any looping using C#

后端 未结 28 1428
天命终不由人
天命终不由人 2020-12-22 19:30

I am trying to print numbers from 1 to 100 without using loops, using C#. Any clues?

28条回答
  •  [愿得一人]
    2020-12-22 20:16

    Enumerable.Range(1, 100)
        .Select(i => i.ToString())
        .ToList()
        .ForEach(s => Console.WriteLine(s));
    

    Not sure if this counts as the loop is kind of hidden, but if it's legit it's an idiomatic solution to the problem. Otherwise you can do this.

        int count = 1;
    top:
        if (count > 100) { goto bottom; }
        Console.WriteLine(count++);
        goto top;
    bottom:
    

    Of course, this is effectively what a loop will be translated to anyway but it's certainly frowned upon these days to write code like this.

提交回复
热议问题