As a mental exercise, I just wanted to practice coding this part. This is mainly taught in programming courses to sort of explain how nested loops work. Here's a program that prints different staircase patterns based on a given integer number, N.
I personally would recommend you to try printing and forming the logic to print patterns by yourself first and then try looking up the solution.
Pattern #1
###
###
####
#####
void progressiveStaircase(int number)
{
for (int i = 0; i < number; i++)
{
for (int j = 0; j <= i; j++)
{
cout << "#";
}
cout << endl;
}
}
Pattern #2
####
###
##
#
void reverseStaircase(int number)
{
for (int i = 0; i < number; i++)
{
for (int j = i; j < number; j++)
{
cout << "#";
}
cout << endl;
}
}
Pattern #3
###
###
####
#####
void progressiveStaircaseRight(int number)
{
for (int i = 0; i < number; i++)
{
for (int j = 0; j < number; j++)
{
if (i + j >= number - 1)
{
cout << "#";
}
else
{
cout << " ";
}
}
cout << endl;
}
}
Pattern #4
#####
####
###
##
#
####
###
##
#
void progressiveStaircaseLeft(int number)
{
for (int i = 0; i < number; i++)
{
for (int j = 0; j < number; j++)
{
if (i <= j)
{
cout << "#";
}
else
{
cout << " ";
}
}
cout << endl;
}
Pattern #5 - Pyramid
#
###
#####
#######
#########
void pyramid(int number)
{
int row = number;
number = number * 2;
if (number % 2 == 0)
{ // normalizing number so has equal amount of number on both sides.
number = number + 1;
}
int mid = number / 2; // not adding 1 because loop starts from 0. 5= 5/2= 2 = 0 1 2 3 4 = 2 mid
cout << "row=" << row << " column=" << number << " mid=" << mid << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < number; j++)
{
if (j <= mid + i && j >= mid - i)
{
cout << "#";
}
else
{
cout << " ";
}
}
cout << endl;
}
}
Output of all patterns altogether :
0 Comments