In this post, we will learn how to print a right angled triangle star pattern with the help of python. This is post under the category Build Concepts in Coding
Approach
Our approach will be simple. We will run two for loops. The first for loop will help us to move from top to bottom and the second for loop will help us to move from left to right. So with the help of these two loops.
Here we will use one condition also inside the second for loop we will check whether X is greater than or equal to Y or not. This condition help us to print the desired triangle.
Algorithm To Right Angled Triangle Star Pattern
Here is the step-by-step algorithm for better understanding.
- Take height from user input.
- Now we run nested for loops
- Initialize x=0
- First for loop: repeat steps from 5 to 9 till x is less than height.
- Initialize y=0
- Second for loop: Repeat steps 7 till y is less than or equal to x+1.
- print * (star)
- break inner for loop
- print next line
- break outer for loop
Python Code To Print Right Angled Triangle Star Pattern
In this code, we have used the if condition in line 9 to check whether >=y or not.
#function to print pattern
def drawRightAngledTriangle(height):
#first for loop from go to top to bottom
for x in range(0, height):
#second for loop to move left to right
for y in range(0, height):
#check condition if x is greter then or equal to y
# then print *
if x>=y:
print(' * ', end='')
print('')
height = int(input("Enter the height of triangle "))
drawRightAngledTriangle(height )
In this code, we have limited the for loop to run only for x times so it is a better approach with respect to time complexity.
#function to print pattern
def drawRightAngledTriangle(height):
#first for loop from go to top to bottom
for x in range(0, height):
#second for loop to move left to right
for y in range(0, x+1):
#check condition if x is greter then or equal to y
# then print *
print(' * ', end='')
print('')
height = int(input("Enter the height of triangle "))
drawRightAngledTriangle(height )
Output of the following code will be
If you have any queries regarding this code, comment on your problem below.