Printing Character patterns is a classic programming exercise that helps beginners understand nested loops and control structures in C++. Here, I will provide a simple C++ program to print a character pattern, specifically a pyramid made of letters. This example will increment the letters alphabetically as it builds the pyramid.
Example: Alphabet Pyramid Pattern
This program will create a pyramid where each row contains the same character, starting from ‘A’ in the first row, ‘B’ in the second, and so on.
- C++ Code:
#include <iostream>
using namespace std;
int main() {
int rows;
// User inputs the number of rows for the pattern
cout << “Enter the number of rows: “;
cin >> rows;
// Print the character pattern
for (int i = 1; i <= rows; ++i) { // Outer loop for each row
for (int j = rows – i; j > 0; –j) { // Inner loop for leading spaces
cout << ” “;
}
for (int k = 1; k <= 2 * i – 1; ++k) { // Inner loop for characters
cout << char(‘A’ + i – 1); // Print character corresponding to row number
}
cout << endl; // Move to the next line after each row is complete
}
return 0;
}
Explanation:
-
Header and Namespace:
The program includes <iostream> for input and output operations and uses the std namespace.
- Input:
The program prompts the user to enter the number of rows. This value determines the height of the pyramid.
- Outer Loop:
This loop runs from 1 to rows, where each iteration represents a row in the pyramid.
-
First Inner Loop:
This loop prints spaces before the characters on each row. The number of spaces decreases as the row number increases, creating the left alignment of the pyramid.
-
Second Inner Loop:
This loop prints characters. It calculates the number of characters to print based on the row number (2 * i – 1). All characters in a single row are the same and correspond to their row number in the alphabet (char(‘A’ + i – 1)).
- Output:
Each character is printed next to each other without spaces in this version, and each row ends with a newline.
Program Output:
If the user enters 4 for the number of rows, the output will be:
A
BBB
CCCCC
DDDDDDD
This program is a straightforward demonstration of using nested loops and ASCII arithmetic to create patterns in C++. Adjusting the loops and the logic for character calculation allows creation of various other patterns and designs.