Interview Question
Software Engineer / DevelopersCountry: India
I know this is lame, but here is what I could think of:
public class Print100Times {
int i=0;
public void method1(int elementToBePrinted)
{
if(++i<=100)
{
System.out.print(elementToBePrinted);
method2(elementToBePrinted);
}
}
private void method2(int elementToBePrinted) {
if(++i<=100)
{
System.out.print(elementToBePrinted);
method1(elementToBePrinted);
}
}
public static void main(String[] args)
{
Print100Times p=new Print100Times();
p.method1(0);
}
}
There is no loop and technically speaking there is no recursion either. :P
I too came up with the same method ... (I kind of agree on the "lame" part :p).
However, is it still considered recursion ?
That is recursion. The fact that it uses two methods does not affect the fact that it is a recursive algorithm.
#include<stdio.h>
int main()
{
int i=1;
label:
if(i<=1000)
{
printf("%d ",i++);
goto label;
}
return 0;
}
Toggle between functions:
#include<iostream>
using namespace std;
void func1(int n, int k);
void func2(int n, int k);
void func1(int n, int k) {
if(n>0) {
cout<<k<<endl;
n--;
func2(n, k);
}
}
void func2(int n, int k) {
if(n>0) {
cout<<k<<endl;
n--;
func1(n, k);
}
}
int main() {
func1(1000, 10);
system("pause");
return 0;
}
Are we talking about loops at the assembly level?
When building this with g++ -std=c++11 -ftemplate-depth=1000, this generates a binary without loops.
#include <iostream>
#include <functional>
typedef std::function<void(unsigned i)> CallbackFn;
template<unsigned i>
struct Looper
{
static void loop(CallbackFn fun)
{
fun(i);
Looper<i - 1>::loop(fun);
}
};
template<>
struct Looper<0>
{
static void loop(CallbackFn fun)
{
}
};
int
main (int argc, const char* argv[])
{
int var = 42;
Looper<1000>::loop(
[var] (unsigned i)
{
std::cout << var << std::endl;
}
);
return 0;
}
Found it out from GeeksForGeeks
#include <iostream>
using namespace std;
template<int N>
class PrintOneToN
{
public:
static void print()
{
PrintOneToN<N-1>::print(); // Note that this is not recursion
cout << N << endl;
}
};
template<>
class PrintOneToN<1>
{
public:
static void print()
{
cout << 1 << endl;
}
};
int main()
{
const int N = 100;
PrintOneToN<N>::print();
return 0;
}
I find a type called "Dynamic Recursion" under Recursion Types.
Can you give me the link for its definition?
#include<iostream>
- Anonymous April 22, 2013#include<vector>
using namespace std;
class A
{
public:
A(int x )
{
cout<<x<<endl;
}
};
int main()
{
int x = 10;
vector<A> a(1000,x);
}