Reputation: 85
So I have to make a program that prints out a triangle of numbers in a sense that if, let's say, the input is triangleOfNumbers(1, 5)
it prints out:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
I quickly figured how to do it with loops:
for (int i = start; i <= end; i++) {
for (int j = start; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
But as much as I hit my head against the wall I just can't figure out how to do it with recursion. I'm actually starting to think that I'm no good for programming if I can't figure such a simple thing out.
Anyways.. any solution or tip would be appreciated! If you'd want to get more into details and actually explain what's going on in said recursion it would be even better!
Upvotes: 1
Views: 4958
Reputation: 1
This code help you to print such pattern.
public String triangle(int n){
if(n<=0){
return "";
}else{
String p=triangle(n-1);
p=p +""+ (n);
System.out.println(p);
return p;
}
}
Upvotes: 0
Reputation: 16711
The first function recursively fills a row. Starting at a number the function keeps concatenating numbers as strings until one is reached and the recursion stops. The second function does the same thing except concatenating rows until the lower bound reaches the upper bound.
public class Test
{
public static String row(int n)
{
if (n == 1)
return "1";
else
return row(n - 1) + " " + n;
}
public static String triangle(int a, int b)
{
if (a == b)
return row(b);
else
return row(a) + "\n" + triangle(a + 1, b);
}
public static void main(String[] args)
{
System.out.println(triangle(1, 10));
}
}
Upvotes: 2