Alex Rivera | Logout

C: Looping without using looping statements or recursion

Asked 2009-10-14T08:17:52.600
14

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?

Edit
Report

4 Answers

7

You can use setjmp and logjmp functions to do this as shown in this C FAQ

For those who are curious to why someone have a question like this, this is one of the frequently asked questions in India for recruiting fresh grads.

answered 2009-10-14T08:44:08.377
5

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...

answered 2009-10-14T08:27:55.257
1
 #include "stdio.h"

 #include "stdlib.h"

 #include "signal.h"

 int g_num;

 int iterator;

 void signal_print()

 {

        if(iterator>g_num-1)

                exit(0);

        printf("%d\n",++iterator);

 }

 void myprintf(int n)

 {

     g_num=n;

        int *p=NULL;

     int x= *(p); // the instruction is reexecuted after handling the signal

 }

 int main()

 {

        signal(SIGSEGV,signal_print);

        int n;

        scanf("%d",&n);

        myprintf(n);

        return 0;

 }
answered 2011-02-02T17:40:34.870
-1
    /// <summary>
    /// Print one to Hundred without using any loop/condition.
    /// </summary>
    int count = 100;
    public void PrintOneToHundred()
    {
        try
        {
            int[] hey = new int[count];
            Console.WriteLine(hey.Length);
            count--;
            PrintOneToHundred();
        }
        catch
        {
            Console.WriteLine("Done Printing");
        }
    }
answered 2010-01-12T13:50:00.087

Your Answer