C: Looping without using looping statements or rec

2020-05-23 06:35发布

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 loops, goto statement, recursion, and switch statement. Is it possible?

标签: c loops
16条回答
一纸荒年 Trace。
2楼-- · 2020-05-23 07:25
#include <stdlib.h>

int callback(const void *a, const void *b) {
    static int n = 1;

    if (n <= N)
        printf("%d\n", n++);

    return 0;
}

int main(int argc, char *argv) {
    char *buf;
    /* get N value here */

    buf = malloc(N);  // could be less than N, but N is definitely sufficient
    qsort(buf, N, 1, callback);
}

I think it doesn't count as recursion.

查看更多
疯言疯语
3楼-- · 2020-05-23 07:26

You can do this by nesting macros.

int i = 1;

#define PRINT_1(N) if( i < N ) printf("%d\n", i++ );
#define PRINT_2(N) PRINT_1(N) PRINT_1(N)
#define PRINT_3(N) PRINT_2(N) PRINT_2(N)
#define PRINT_4(N) PRINT_3(N) PRINT_3(N)
:
:
#define PRINT_32(N) PRINT_31(N) PRINT_31(N)

There will be 32 macros in total. Assuming size of int as 4 bytes. Now call PRINT_32(N) from any function.

Edit: Adding example for clarity.

void Foo( int n )
{
    i = 1;

    PRINT_32( n );
}


void main()
{
    Foo( 5 );
    Foo( 55 );
    Foo( 555 );
    Foo( 5555 );
}
查看更多
Rolldiameter
4楼-- · 2020-05-23 07:27

Another thingy (on linux) would be to do as below where 7 is N

int main() {
    return system("seq 7");
}
查看更多
beautiful°
5楼-- · 2020-05-23 07:30

This does it:

int main ()
{
printf ("1 to N one per each line\n");
return 0;
}

Here is another one:

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

int main (int c, char ** v) {
    char b[100];
    sprintf (b, "perl -e 'map {print \"$_\\n\"} (1..%s)'", v[1]);
    system (b);
    return 0;
}
查看更多
登录 后发表回答