Let’s go through the logic for printing Triangle Pattern:
- Step - 1. Ask User for Number of rows in the Triangle.
- Step - 2. Iterate from First row to Last.
- Step - 3. Get the number of Space for the row and Print them.
- Step - 4. Get the number of * for every row and print them.
- Step - 5. Give a line break in order to go into the next line for next row.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi10-rjAVrrlefK-V3ldycwSyAEI-0YoC-VZZRDIubZ63dsEWeoQBhCj7iszrT-sJL_DFkamebR_ajNw3yLgAJ8pm-Orf22tuXN8QxEaJy2y7QPUcXh8SWt1RUHctKWyrdXt7GkltzMW5GC/s1600/Triangle+Pattern.png)
Code for Triangle Pattern in Java:
package com.missTechy;
import java.util.Scanner;
public class Triangle {
public static void main(String[] args)
{
// Ask the user for triangle size.
System.out.println("Enter the triangle size :: ");
// Create an instance of Scanner class present in util package.
// Object of scanner class is used to take input from user.
Scanner scanner = new Scanner(System.in);
// Normally when scanner class object is used then it get the value in String format.
// scanner object calls nextInt() method which is used to convert String into Int.
int rows = scanner.nextInt();
// This variable is used to print the number of * in a row.
int k = 0;
// iterate from first row to last row.
for(int i = 1; i <= rows; i++)
{
// create the space before printing *.
// number of space in the starting of a row must be equal to the (total number of rows - current row number).
for(int space = 1; space <= rows - i; space++)
{
// Print space only.
System.out.print(" ");
}
// while loop is used to print the number of * in a row.
// number of * in a row must be one less than the double of the number of row (2*currentRow -1).
while(k != 2 * i - 1)
{
System.out.print("* ");
// increment k so that the next * will print
k++;
}
// used as break just to come into another line.
System.out.println();
// initialize k to 0 in order to initialize the number of printed * for the next line to 0.
k = 0;
}
}
}
Output of Triangle Pattern in Java:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmeNOZ9-D7sB9bRUkXlj_sVh0aKWInCPisuYH6jFMTm6SSsAVXGhgcKt0wuZikNWQAVLSfIZyNmPCIG5VDqZi6TnXx_H1ojxt8mjvgy-u38FcPt6n1vu6DrGGFARkpUUxaJWEc7Ex2Pq_p/s1600/Triangle+Pattern+Outut.png)
3 Comments
Great
ReplyDeleteWow..đŸ˜±đŸ˜± This is awesome. finally I got the solution of my problem. Thank you so much MissTechy
ReplyDeleteThanks alot.
Delete