23 December 2013

Print numbers from 1 to 1000 without using any loop or conditional statements. Don’t just write the print() or cout or Console.Write() or anything like this.

I write a C# version reference the C version.

Action<int> action = null;

action = x => {  // <=> Console.Write(x.ToString().PadRight(4));
            	Console.Write("{0,-4}", x.ToString()); 
                action += r => { return; };
                action.GetInvocationList()[x / 1000].DynamicInvoke(x + 1);
              };
action(1);
Action<int> action = null;

action = x =>
{
    Console.Write("{0,-4}", x.ToString());
    action.GetInvocationList()[x / 100].DynamicInvoke(++x);
};
action += y => { };

action(1);

C version:

#include <stdio.h>
#include <stdlib.h>

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}

stackoverflow