Printing a Right Triangle in Java

Printing the Right Triangle in Java
Let us print a right angled triangle on the console in Java. Doing this is very simple if you put a very little effort. The following code sample illustrates how this can be achieved.







import java.util.*;
class RightTriangle
{
    public static void main(String args[])
    {

    Scanner s=new Scanner(System.in);

    System.out.println("Enter the base length (chars)");
    int n=s.nextInt();

    System.out.println("Enter the char");
    char st=s.next().charAt(0);
   
        for(int i=0;i<=n;i++)
        {
            for(int j=0;j<i+1;j++)
            {
            System.out.print(st);
            }
        System.out.println();
        }   
    }
}

Sample Output


Enter the base length (chars)
10
Enter the char
`
`
``
```
````
`````
``````
```````
````````
`````````

Explanation

n is an integer which represents the base length i.e. the no.of chars in the last line.
st represents the char that is to be used to draw the right angled triangle.
The two loops together draw the right angled triangle. Let us first consider the inner loop.
The inner loop is dedicated to print the required no.of given chars. It is obvious that the loop condition fails, whenever j becomes i+1.
The outer loop, rotates from 0 till the value of n (base length).
The inner loop rotate from 0 to i+1. Let us analyze the program for better understand.

For the first time


i=0;
j=0; j<0+1? (true) -> Print a `
j++; (j=1)
1<1? (false) -> Exit inner loop -> System.out.println();
i++; (i=1);

For the second time


i=1;
j=0; j<1+1? (true) -> Print a `
j++; (j=1); 1<1+1? (true) -> Print a `
j++; (j=2);
2<2? (false); -> Exit inner loop -> System.out.println();

This continues so on, it depends upon the value of n. Whatever, a right angled triangle is printed and this how we can achieve this in Java.

No comments: