I have this function:
public void func1(int d, double delta, double min, double max )
{
if( d == 1 )
{
for( double i=min ; i <= max ; i++ )
System.out.println(i);
}
if(d == 2 )
{
for( double i=min ; i <= max ; i++ )
for( int j = min ; j <= max ; j++ )
System.out.println(i, j);
}
if(d == 3 )
{
for( double i=min ; i <= max ; i++ )
for( int j = min ; j <= max ; j++ )
for( int k=min ; k <= max ; k++ )
System.out.println(i, j, k );
}
}
How to make it dynamic? I.e.,: how to not use the if statement so that the function can work with any given d?
Currently, if I want the function to work with d=5, then I have to write five nested for loops and add an if statement.
You can use the idea of Recursion to tackle this problem. The key idea is that if you want to have
dloops, you can simply have a single for-loop, and within that for-loop you will have a function that loopsd - 1times:You may refer to the following sample code for reference:
Update
I have modified the code in order to return an array of the double values instead of a string: