how do i write a java code preferably using the 'while-do', 'if-else', 'for' statements to get these outcomes?

n is the input and the system prints triangles of height n?


n=2

. *
***

n=5

........*
......***
....*****
..*******
*********

ignore the dots, they are to align them properly

thanks in advance

Recommended Answers

All 2 Replies

public class Triangle {

    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);

        // Loop N times, one for each row
        for (int i = 0; i < N; i++) {

            // Print j periods
            for (int j = 0; j < i; j++)
                System.out.print(". ");

            // Print N-i asterisks
            for (int j = 0; j < N - i; j++)
                System.out.print("* ");

            // print a new line
            System.out.println();
        }
    }
}
public class Triangle {

    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);

for (int i = 0; i < N; i++)
        {
            int stars = 1 + 2 * (i);
            int space = N - i;
            for (int j = 0; j < space; j++)
            {
                System.out.print("  ");
            }
            
            for (int k = 0; k < stars; k++)
            {
                System.out.print("* ");
            }
            System.out.println();
        }
commented: This forum is not for you to do others people homework -1

Hi ordi. You are new here so you must learn that you shouldn't give the code for others people assignments. This is not that kind of forum.

When someone's post their assignment and nothing more don't give the complete solution. It violates the rules.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.