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.
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;
}
}
}
3 Comments
Great
ReplyDeleteWow..đŸ˜±đŸ˜± This is awesome. finally I got the solution of my problem. Thank you so much MissTechy
ReplyDeleteThanks alot.
Delete