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
int x=1;
void PRINT_2(int);
void PRINT_1(int n)
{ if(x>n)
return;
printf("%d\n",x++);
PRINT_2(n);
}
void PRINT_2(int n)
{ if(x>n)
return;
printf("%d\n",x++);
PRINT_1(n);
}
int main()
{ int n;
scanf("%d",&n);
if(n>0)
PRINT_1(n);
system("pause");
}
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.
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();
...
}
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...
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 :)
Another thingy (on linux) would be to do as below where 7 is N
int main() {
return system("seq 7");
}