Reputation: 1508
I got this question from my friend who underwent an interview. The interviewer asked him to Generate the Fibonacci series without using any function except main.
Means he was supposed to generate a Fibonacci series by calling the main()
function recursively, but he wasn't able to do that. I also tried after his interview but all in vain.
Could anyone please tell their ideas in this regard?
Upvotes: 0
Views: 695
Reputation: 181725
Simple. In C:
#include<stdio.h>
main(b,a){a>b?main(1,0):printf("%d\n",a),main(a+b,b);}
In Java you need more code and a lot more memory and it only goes up to 65535:
class F{public static void main(String[]v){int x=v.length,a,b;System
.out.println(a=x>>16);main(new String[(b=x&0xFFFF)+1<<16|a+b]);}}
Would I get hired?
Upvotes: 2
Reputation: 145829
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
static int i = 0, j= 1;
int res, max;
/*
* You could add some check for argc and argv
*/
max = atoi(argv[1]);
printf("%d ", i);
res = i + j;
i = j;
j = res;
if (j > max)
{
printf("\n");
exit(0);
}
main(argc, argv);
}
Example:
$ gcc -std=c99 -Wall tst.c -o tst
$ ./tst 1000
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
$
Upvotes: 1
Reputation: 1316
#include <stdio.h>
int fib1=0;
int fib2=1;
int fib_tmp;
int main()
{
printf("%d ",fib1);
fib_tmp=fib1+fib2;
fib1=fib2;
fib2=fib_tmp;
if (fib1>0)
main();
}
Silly interview questions ...
Well at least it compiles and gives accurate result for ints.
It generates the sequence "recursively" for all int representable fibonacci number :)
Upvotes: 1