Your code should look like this
public static void main(String[] args) {
recusiveFunction(1,10); // First parameter is the iteration number and 2 is total times.
}
private static void recusiveFunction(int iteration ,int total) {
String str="";
for(int i=1;i<=iteration;i++){ // this loops creates what it needs to print 1 or 12 or 123
str+=i;
}
if(iteration<total/2){
System.out.println(str);
recusiveFunction(++iteration,total);
}
System.out.println(str);
}
Output:
1
12
123
1234
12345
1234
123
12
1
How this works is the we store the string in a variable that we want to print but we keep calling the function and increment the string is the iteration are less than half. then once it reaches half it start returning the stack trace so it gives us the return output in decreasing order.
Edit :
As said by pshemo modified the code a little bit to have absolutely no loops:
public static void main(String[] args) {
recusiveFunction(1,10,"");
}
private static void recusiveFunction(int iteration ,int total, String str) {
str+=iteration;
if(iteration<total/2){
System.out.println(str);
recusiveFunction(++iteration,total,str);
}
System.out.println(str);
}
Output:
1
12
123
1234
12345
1234
123
12
1
Alternative way:
public class Main {
private static int iteration=1;
private static String str ="";
public static void main(String[] args) {
printSequence(10);
}
private static void printSequence(int total) {
if(iteration<=total){
str+=iteration;
System.out.println(str);
iteration++;
printSequence(total);
}
if(2*total - iteration >0) {
str = str.substring(0, 2 * total - iteration);
iteration++;
System.out.println(str);
}
}
}
Output:
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
123456789
12345678
1234567
123456
12345
1234
123
12
1