This code
demonstrates simple functions of patterns that are useful for beginner in C/C++
coding. A namespace `Pattern` is defined to access all pattern functions so
that they can be used in one main function.
The code is simple enough and can
be understood if you know the basic `for loop`.
Source code:
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
namespace Pattern
{
/*
Simple Half Pyramid
Function Output:
*
*
*
*
* *
*
* * *
*
* * * *
.......nth row
*/
void HalfPyramid(int rows)
{
for (int i =
1; i <= rows; ++i)
{
for (int j =
1; j <= i; ++j)
{
cout << "* ";
}
cout << "\n";
}
}
/*
Simple Inverted Half Pyramid
Output of the function:
.......nth row
*
* * * *
*
* * *
*
* *
*
*
*
*/
void IHalfPyramid(int rows)
{
for (int i
= rows; i >= 1; --i)
{
for (int j =
1; j <= i; ++j)
{
cout << "* ";
}
cout << endl;
}
}
/*
Pyramid
Output:
*
* * *
* * * * *
* * * * * * *
nth
row....
*/
void Pyramid(int rows)
{
int space;
for (int i =
1, k = 0; i <= rows; ++i, k = 0)
{
for (space
= 1; space <= rows - i; ++space)
{
cout << " ";
}
while (k
!= 2 * i - 1)
{
cout << "* ";
++k;
}
cout << endl;
}
}
/*
Inverted Pyramid
Output:
......nt row
* * * * * * *
* * * * *
* * *
*
*/
void IPyramid(int rows)
{
for (int i
= rows; i >= 1; --i)
{
for (int space
= 0; space < rows - i; ++space)
cout << " ";
for (int j =
i; j <= 2 * i - 1; ++j)
cout << "* ";
for (int j =
0; j < i - 1; ++j)
cout << "* ";
cout << endl;
}
}
/*
Half Pyramid In Mirror
Function Output:
*
* *
* * *
* * * *
*
* * * *
.......nth row
*/
void HalfPyramidInMirror(int rows)
{
for (int i =
1; i <= rows; ++i)
{
for (int j
= rows - i; j >= 0; --j)
cout << " ";
for (int k =
1; k <= i; k++)
cout << " *";
cout << endl;
}
}
/*
Inverted Half Pyramid In Mirror
Function Output:
......nth row
* * * * *
* * * *
* * *
* *
*
*/
void IHalfPyramidInMirror(int rows)
{
for (int i
= rows; i >= 1; --i)
{
for (int j
= rows - i; j >= 0; --j)
cout << " ";
for (int k =
1; k <= i; k++)
cout << "* ";
cout << endl;
}
}
/*
Pascal Triangle
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
.......nth row
*/
void PascalTriangle(int rows)
{
int coef
= 1;
for (int i =
0; i < rows; i++)
{
for (int space
= 1; space <= rows - i; space++)
cout << " ";
for (int j =
0; j <= i; j++)
{
if (j
== 0 || i == 0)
coef = 1;
else
coef = coef*(i - j + 1) / j;
cout << coef << " ";
}
cout << endl;
}
}
}
int main()
{
Pattern::HalfPyramid(4);
Pattern::IHalfPyramid(4);
Pattern::HalfPyramidInMirror(4);
Pattern::IHalfPyramidInMirror(4);
Pattern::Pyramid(4);
Pattern::IPyramid(4);
Pattern::PascalTriangle(4);
_getch();
return 0;
}
Output: