Chaklader
Chaklader

Reputation: 169

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.

Upvotes: 0

Views: 347

Answers (3)

alexbt
alexbt

Reputation: 17045

Here's an iterative approach. Also, the number of stars can be calculated with the formula n(n+1)/2:

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

triangular(4):

****
***
**
*
10

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191728

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

Upvotes: 4

Chaklader
Chaklader

Reputation: 169

It has an issue with the for loop and I changed the code. It works fine now and here it is:

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; ) {

            System.out.print("* ");

            count = count + 1 ;
            i++;

            if(i == n){

                System.out.println();

                return triangular(n-1, count);
            }
        }
        return count; 
    }

Upvotes: 0

Related Questions