C: Looping without using looping statements or recursion

前端 未结 16 1841
走了就别回头了
走了就别回头了 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:47

    write all possible output to a string first, and null terminate it where the output should stop.
    this is a rather dirty solution, but given the limitations, all I can think of,
    except for using assembler, off course.

    char a[]="1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n"/*...*/;
    main(n,v)char**v;{n=atoi(v[1]);
    #define c(x)(n>x?n-x:0)
    a[n+c(1)+c(9)+c(99)+c(999)+c(9999)+c(99999)+c(999999)+c(9999999)/*+...*/]=0;
    puts(a);}
    

    Given that MAX_INT==2147483647 on popular architectures, we only need to go up to +c(999999999). Typing out that initial string might take a while, though...

提交回复
热议问题