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

后端 未结 28 1232
天命终不由人
天命终不由人 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:19

    A completely unnecessary method:

    int i = 1;
    System.Timers.Timer t = new System.Timers.Timer(1);
    t.Elapsed += new ElapsedEventHandler(
      (sender, e) => { if (i > 100) t.Enabled = false; else Console.WriteLine(i++); });
    t.Enabled = true;
    Thread.Sleep(110);
    
    0 讨论(0)
  • 2020-12-22 20:21

    I can think of two ways. One of them involves about 100 lines of code!

    There's another way to reuse a bit of code several times without using a while/for loop...

    Hint: Make a function that prints the numbers from 1 to N. It should be easy to make it work for N = 1. Then think about how to make it work for N = 2.

    0 讨论(0)
  • 2020-12-22 20:21

    Feeling a bit naughty posting this:

       private static void Main()
        {
            AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
            {
                var frames = new StackTrace().GetFrames();
                Console.Write($"{frames.Length - 2} ");
                var frame = frames[101];
            };
    
            throw new Exception();
        }
    
    0 讨论(0)
  • 2020-12-22 20:22
    PrintNum(1);
    private void PrintNum(int i)
    {
       Console.WriteLine("{0}", i);
       if(i < 100)
       {
          PrintNum(i+1);
       } 
    }
    
    0 讨论(0)
提交回复
热议问题