C: Looping without using looping statements or recursion

前端 未结 16 1848
走了就别回头了
走了就别回头了 2021-02-04 07:56

I want to write a C function that will print 1 to N one per each line on the stdout where N is a int parameter to the function. The function should not use while, for, do-while

16条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 08:48

    If you know the upper limit of N you can try something like this ;)

    void func(int N)
    {
        char *data = " 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n";
        if (N > 0 && N < 12)
            printf("%.*s", N*3, data);
        else
            printf("Not enough data. Need to reticulate some more splines\n");
    }
    

    Joke aside, I don't really see how you can do it without recursion or all the instructions you mentioned there. Which makes me more curious about the solution.

    Edit: Just noticed I proposed the same solution as grombeestje :)

提交回复
热议问题