Last updated on February 27th, 2019 at 10:10 am
As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a Java program to Draw An Equilateral Triangle Using Stars Of Given Row.
Problem statement: Draw an Equilateral Triangle using stars of given row.
Example: An Equilateral Triangle of 5 rows:
- Number of stars in a row is equal to row number. For example: First row has one star, Second row has two stars and so on.
- We must need to decide number of spaces to be printed before printing first star in first row. It will help in drawing proper Equilateral Triangle.
- Notice first row, first star is printed at column number which is equal to total number of rows. So we need to fill remaining indexes of columns with spaces.
- Notice second row, two stars occupy columns indexes (total no of rows) and (total no of rows-1) . So for second row, you need to put spaces for remaining columns.
- You must have got idea of pattern now. You need to keep reducing number of space by one for each new row.
- If you are still confuse with how many number of spaces you need to provide, just pass (2*Total no of rows). Disadvantage of this is that your triangle will not be left aligned.
- We will have an outer for loop, which will take care of number of rows in triangle.
- We need to use two inner for loop. First inner loop will help us in printing spaces before printing star. Second inner for loop will help in printing stars equal to number of current row.
If you have any other logic of solving above problem, please comment. It is always better to know more logic.
If you like my posts, please like, comment, share and subscribe.
Author: Amod Mahajan
My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning