Chaklader - 3 months ago 18

Java Question

I wrote the program to print a triangle of stars and also, the sum of the stars forms the triangle. When I make the call

`tringle(3)`

`***`

**

*

And, also it should count the

`sum as 6`

`public static int triangular(int n) {`

int count = 0;

count = triangular(n, count);

return count;

}

public static int triangular(int n, int count_){

int count = count_;

if(n == 0)

return count;

if(n < 0)

return -1;

for (int i = 0; i < n; i++) {

System.out.print("* ");

count = count + 1 ;

if(i == n){

return triangular(n-1, count);

}

}

System.out.println();

return count;

}

How do i improve the code ? Now, it prints

`* * *`

3

Please, advise.

Answer

You don't need more than one parameter... 3 + 2 + 1 + 0 = 6.

```
public static int triangular(int n){
if(n <= 0) return 0;
for (int i = 0; i < n; i++) {
System.out.print("* ");
}
System.out.println();
return n + triangular(n - 1);
}
```