Chaklader Chaklader - 29 days ago 9
Java Question

How do I make a triangle of stars and counts the number of stars?

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)
, it should print as the following,

***
**
*


And, also it should count the
sum as 6
and returns it. However, the code is not working as expected that I have provided following,

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);
}
Comments