I have been trying to print elements in
int[][]a= {{2,-36,98},{21,55},{2,5,4,7,6},{101}}
with the help of recursion instead of a loop. Now i have a piece of code with me but it prints extra unwanted elements.
public class RecursionDoubleLoop {
void loop(int[][]a,int x,int y)
{
int n=a.length;
if(x<n)
{
if(y<a[x].length)
{
System.out.println(a[x][y]+" ");
y+=1;
if(y<a[x].length)
loop(a, x, y);
}
y=0;
x+=1;
/*if(x>=n)
{
System.exit(0);
}*/
if(x<n) {
loop(a, x, y);}
}
}
public static void main(String[] args) {
RecursionDoubleLoop obj= new RecursionDoubleLoop();
int[][]a= {{2,-36,98},{21,55},{2,5,4,7,6},{101}};
obj.loop(a, 0, 0);
}
}
Now the Expected Output is
2 -36 98 21 55 2 5 4 7 6 101
My output
2 -36 98 21 55 2 5 4 7 6 101 101 101 101 101 2 5 4 7 6 101 101 101 101 101 21 55 2 5 4 7 6 101 101 101 101 101 2 5 4 7 6 101 101 101 101 101 21 55 2 5 4 7 6 101 101 101 101 101 2 5 4 7 6 101 101 101 101 101
Tried debugging but ultimately had to uncomment the System.exit(0) function.
It will be very helpful if someone can point out the error.