Pattern – Inverted right half triangle of symbol
Printing the inverted right half triangle made of same symbol as per row count given by the user.
Learning Objectives
- Use of nested for loop for printing the inverted-half right angle triangle pattern made of a symbol.
Source Code
|
|
Related ( ? ) : |
Run Output
Code Understanding
int cnt; cout<<“Give row count : “; cin>>cnt;
We collect the row count from the user. This count is also used for the column count to keep reasonable symmetry of the pattern.
for(int i=1;i<=cnt;i++)
This is outer loop which help us count the rows. For this reason this starts from 1 and goes up to the value of variable cnt as given by the user.
{
for(int j=cnt;j>=i;j–)
This is inner loop which begins with the cnt value and in each iteration of row it changes the comparison limit which is based on the row count. As third instruction of condition it decreases the j count so that the in first row the number of columns is same as row and then they subsequently reduce by 1 each time.
{
cout<<“*”; //Here we print the desired symbol
}
cout<<“n”; //Here we change to next row before moving to the out loop top.
}
Notes
- Any symbol, alphabet or number can be used for such patterns.
- Replacing ‘*’ with i, j, or char(i+64) can build newer interesting patterns.
- Observe the difference between inverted and upright patterns.
for(int j=cnt;j>=i;j–) //For inverted pattern.
for(int j=1;j<=i;j++) //For upright pattern.
Common Errors
- The inner loop instructions can make lot of difference if not initialised properly. To avoid error a student is advised to make changes and try to dry run the loop for understanding the difference.
Suggested Filename(s): pat-inv-hrht.cpp
Created: 10-Jan-2018 23:23 | Updated: 15-Sep-2018 13:40|
