20 Pattern Programs in C++
Five star patterns in one C++ file (right, left, full, inverted, diamond). rows is hardcoded to 5.
IntermediateAdvanced Pattern ProgramsExample 6 of 6
20-pattern-programs.cpp
1#include <iostream>2using namespace std;34int main() {5 int rows = 5;67 // Pattern 1: Right Half Pyramid8 cout << "Pattern 1 - Right Half Pyramid:" << endl;9 for (int i = 1; i <= rows; i++) {10 for (int j = 1; j <= i; j++) {11 cout << "* ";12 }13 cout << endl;14 }1516 // Pattern 2: Left Half Pyramid17 cout << "\nPattern 2 - Left Half Pyramid:" << endl;18 for (int i = 1; i <= rows; i++) {19 for (int j = 1; j <= rows - i; j++) {20 cout << " ";21 }22 for (int j = 1; j <= i; j++) {23 cout << "* ";24 }25 cout << endl;26 }2728 // Pattern 3: Full Pyramid29 cout << "\nPattern 3 - Full Pyramid:" << endl;30 for (int i = 1; i <= rows; i++) {31 for (int j = 1; j <= rows - i; j++) {32 cout << " ";33 }34 for (int j = 1; j <= 2 * i - 1; j++) {35 cout << "*";36 }37 cout << endl;38 }3940 // Pattern 4: Inverted Pyramid41 cout << "\nPattern 4 - Inverted Pyramid:" << endl;42 for (int i = rows; i >= 1; i--) {43 for (int j = 1; j <= rows - i; j++) {44 cout << " ";45 }46 for (int j = 1; j <= 2 * i - 1; j++) {47 cout << "*";48 }49 cout << endl;50 }5152 // Pattern 5: Diamond53 cout << "\nPattern 5 - Diamond:" << endl;54 for (int i = 1; i <= rows; i++) {55 for (int j = 1; j <= rows - i; j++) {56 cout << " ";57 }58 for (int j = 1; j <= 2 * i - 1; j++) {59 cout << "*";60 }61 cout << endl;62 }63 for (int i = rows - 1; i >= 1; i--) {64 for (int j = 1; j <= rows - i; j++) {65 cout << " ";66 }67 for (int j = 1; j <= 2 * i - 1; j++) {68 cout << "*";69 }70 cout << endl;71 }7273 return 0;74}
Output
Pattern 1 - Right Half Pyramid:
*
* *
* * *
* * * *
* * * * *
Pattern 2 - Left Half Pyramid:
*
* *
* * *
* * * *
* * * * *
Pattern 3 - Full Pyramid:
*
***
*****
*******
*********
Pattern 4 - Inverted Pyramid:
*********
*******
*****
***
*
Pattern 5 - Diamond:
*
***
*****
*******
*********
*******
*****
***
*What's going on
The file is named like a gallery. The code actually prints five patterns, rows hardcoded to 5. No cin.
1.Right-half:
j <= i, "* "2.Left-half: pad
" " (rows - i) times, then stars3.Full: pad
" ", then 2 * i - 1 times "*"4.Inverted full: i counts down
5.Diamond: full pyramid, then inverted from
rows - 1 so the middle isn't doubledThose are the Pattern Programs pages plus Diamond, concatenated with labels.
Change rows at the top to try 3 or 7. The formulas don't change.
If you came here for twenty separate homeworks, this source only has those five. The earlier pages in this topic (star, triangle, pyramid, number) cover the rest of the usual set.