๐
Date: Feb 4, 2026
๐ฅ Topic: Pyramids, Diamonds & The Butterfly
๐ Handling Spaces
Advanced patterns require us to print Spaces before printing Stars. This usually means we need THREE loops (Outer, Inner-Space, Inner-Star).
1️⃣ Star Pyramid (The Classic)
Calculated logic: Spaces = n - i, Stars = 2*i - 1.
*
***
*****
*******
for(int i=1; i<=n; i++) {
// Spaces
for(int j=1; j<=n-i; j++) {
cout << " ";
}
// Stars
for(int j=1; j<=2*i-1; j++) {
cout << "*";
}
cout << endl;
}
2️⃣ Diamond Pattern
A full diamond is just a Pyramid + Inverted Pyramid.
// Upper Half
for(int i=1; i<=n; i++) {
for(int j=1; j<=n-i; j++) cout << " ";
for(int j=1; j<=2*i-1; j++) cout << "*";
cout << endl;
}
// Lower Half
for(int i=n; i>=1; i--) {
for(int j=1; j<=n-i; j++) cout << " ";
for(int j=1; j<=2*i-1; j++) cout << "*";
cout << endl;
}
3️⃣ The Butterfly Pattern ๐ฆ (Interview Favorite)
This looks complex but it's symmetrical.
* *
** **
*** ***
** **
* *
// Upper Wing
for(int i=1; i<=n; i++) {
// Stars
for(int j=1; j<=i; j++) cout << "*";
// Spaces (2 * (n-i))
int spaces = 2 * (n-i);
for(int j=1; j<=spaces; j++) cout << " ";
// Stars
for(int j=1; j<=i; j++) cout << "*";
cout << endl;
}
// Lower Wing (Reverse Logic)
for(int i=n; i>=1; i--) {
for(int j=1; j<=i; j++) cout << "*";
int spaces = 2 * (n-i);
for(int j=1; j<=spaces; j++) cout << " ";
for(int j=1; j<=i; j++) cout << "*";
cout << endl;
}
⏭️ Next Up: OOPs Concepts
I have mastered Loops, Arrays, Strings, and Logic.
Now it's time to learn the pillar of modern software development: Object Oriented Programming (OOPs).
Classes, Objects, Inheritance... coming soon!
No comments:
Post a Comment