Triangle Pattern in Java
In this class, We discuss Triangle Pattern in Java.
The reader should have prior knowledge of loops in Java. Click Here.
Question:
Given an integer in variable N.
If N = 5, we need to display it as shown below.
1
12
123
1234
12345
We must write a program to display the above output based on the N value.
If N = 6, we need to display six lines of output.
The below diagram shows the program.
Logic:
If N = 5, we display five lines.
If N = 6, we display six lines.
To display the values in a line, we need a loop.
We need to display N lines, so we need a nested loop.
We need a loop to display numbers 1,2,3, 4, and 5.
The above loop should be repeated N times.
The outer loop is used to count the lines.
The inner loop is used to display the numbers.
If i = one, the inner loop should display one number.
If i = two, the inner loop should display numbers 1 and 2.
So we use the i value inside the inner loop to display numbers.
Please understand the above point carefully.