Patterns are an important concept in programming and an excellent way to understand loops in C++. By using nested loops, we can generate different patterns with stars, numbers and other shapes. This article follows the given lecture notes and focuses on implementing such patterns using loops in C++.
Why Learn Patterns?
Patterns are a great way to:
- Understand how loops work.
- Enhance logical and analytical thinking.
- Gain confidence in handling nested loops.
Let’s explore a few patterns.
1. Basic Star Pattern
This pattern prints a single column of stars based on user input:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
cout << "*" << endl;
}
return 0;
}
Input:
5
Output:
*
*
*
*
*
2. Row and Column Star Pattern
This pattern prints a grid of stars using nested loops:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Input:
3
Output:
* * *
* * *
* * *
3. Number Grid Pattern
Instead of *, print the column number (j):
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << j + 1 << " ";
}
cout << endl;
}
return 0;
}
Input:
3
Output:
1 2 3
1 2 3
1 2 3