C++ Pattern Printing Programs
21/04/2024Pattern printing is a popular exercise in programming, especially for learners beginning to understand control structures like loops and conditionals. In C++, you can create a variety of patterns using nested loops.
Square Pattern
This program prints a square pattern of *.
#include <iostream>
using namespace std;
int main() {
int size;
cout << “Enter the size of the square: “;
cin >> size;
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
cout << “* “;
}
cout << endl;
}
return 0;
}
Right Triangle Pattern
This program prints a right triangle aligned to the left.
#include <iostream>
using namespace std;
int main() {
int height;
cout << “Enter the height of the triangle: “;
cin >> height;
for(int i = 1; i <= height; i++) {
for(int j = 1; j <= i; j++) {
cout << “* “;
}
cout << endl;
}
return 0;
}
Inverted Right Triangle Pattern
This program prints an inverted right triangle aligned to the left.
#include <iostream>
using namespace std;
int main() {
int height;
cout << “Enter the height of the triangle: “;
cin >> height;
for(int i = height; i > 0; i–) {
for(int j = 0; j < i; j++) {
cout << “* “;
}
cout << endl;
}
return 0;
}
Pyramid Pattern
This program prints a centered pyramid pattern.
#include <iostream>
using namespace std;
int main() {
int rows;
cout << “Enter the number of rows for the pyramid: “;
cin >> rows;
for(int i = 1; i <= rows; i++) {
// Print spaces
for(int space = 1; space <= rows – i; space++) {
cout << ” “;
}
// Print stars
for(int star = 1; star <= 2 * i – 1; star++) {
cout << “* “;
}
cout << endl;
}
return 0;
}
Diamond Pattern
This program prints a diamond pattern, which combines a pyramid and an inverted pyramid.
#include <iostream>
using namespace std;
int main() {
int n;
cout << “Enter the number of rows for each half of the diamond: “;
cin >> n;
// Upper half
for(int i = 1; i <= n; i++) {
for(int space = 1; space <= n – i; space++) {
cout << ” “;
}
for(int star = 1; star <= 2 * i – 1; star++) {
cout << “* “;
}
cout << endl;
}
// Lower half
for(int i = n-1; i > 0; i–) {
for(int space = 1; space <= n – i; space++) {
cout << ” “;
}
for(int star = 1; star <= 2 * i – 1; star++) {
cout << “* “;
}
cout << endl;
}
return 0;
}
These examples illustrate the basics of pattern printing. Adjusting loop boundaries and nesting levels allows for creating complex and visually appealing patterns. It’s an excellent way to practice loops, nested loops, and conditionals, enhancing problem-solving skills and understanding of program flow in C++.