C: Looping without using looping statements or recursion

前端 未结 16 1884
走了就别回头了
走了就别回头了 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条回答
  •  旧时难觅i
    2021-02-04 08:45

    N is not fixed, so you can't unrole the loop. And C has no iterators as far as I know.

    You should find something that mimics the loop.

    Or thinking outside the box:

    (for example N is limited to 1000, but it is easy to adapt)

    int f(int N) {
        if (N >= 900) f100(100);
        if (N >= 800) f100(100);
        if (N >= 700) f100(100);
        ...
    
        f100(n % 100);
    }
    
    int f100(int N) {
        if (N >= 90) f10(10);
        if (N >= 80) f10(10);
        if (N >= 70) f10(10);
        ...
    
        f(n % 10);
    }
    
    int f10(int N) {
        if (N >= 9) func();
        if (N >= 8) func();
        if (N >= 7) func();
        ...
    }
    

提交回复
热议问题