Pattern 3
Objective
Write a C++ program to print a right half pyramid using alphabets.
Algorithm / Approach
- Use an outer loop
irunning from character'A'to'E'. - Use an inner loop
jrunning from'A'up toi. - Print the character
j. - Print a newline.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(char i = 'A'; i<='E'; i++) {
for(char j = 'A'; j<=i; j++) {
cout<< j;
}
cout<< endl;
}
return 0;
}
Expected Output
A A B A B C A B C D A B C D E
Explanation of the Program
- In C++, characters (
char) are actually just integers under the hood (ASCII values). - Because 'A' is 65 and 'E' is 69, you can literally use a
forloop to iterate directly through the alphabet (i++) just like you would with normal numbers.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)