Descending Start Number Pattern in C++

What You’ll Learn
How to print a pattern where each row starts lower and moves up to 5, then fills the rest with 5:
5 5 5 5 5, 4 5 5 5 5, 3 4 5 5 5, 2 3 4 5 5, 1 2 3 4 5
This is a good exercise for combining multiple inner loops to control a fixed row width.
⭐ Pattern Output
For a maximum value of 5, the pattern looks like this:
5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5Complete C++ Program
First print i..5, then print enough 5s to keep each row at 5 numbers.
#include <iostream>
using namespace std;
int main() {
int maxVal = 5;
int i, j;
for (i = maxVal; i >= 1; i--) {
for (j = i; j <= maxVal; j++) {
cout << j << " ";
}
for (j = 1; j < i; j++) {
cout << maxVal << " ";
}
cout << "\n";
}
return 0;
}🧠 How It Works
Set the maximum value
int maxVal = 5; controls the row width and the final number printed in each row.
Outer loop (choose starting number)
for (i = maxVal; i >= 1; i--) sets the start of each row: 5, 4, 3, 2, 1.
Print the ascending part
for (j = i; j <= maxVal; j++) prints i, i+1, ... up to 5.
Fill remaining positions with 5
for (j = 1; j < i; j++) prints extra 5s so each row has exactly 5 numbers.
Fixed-width number pattern
Each row is built from two parts: an ascending segment and a padding segment of 5s.
Variation — User Input Version
Let the user choose the maximum value (the row width). For best results, use a positive integer.
#include <iostream>
using namespace std;
int main() {
int maxVal;
int i, j;
cout << "Enter the maximum value: ";
cin >> maxVal;
if (!cin || maxVal <= 0) return 0;
for (i = maxVal; i >= 1; i--) {
for (j = i; j <= maxVal; j++) {
cout << j << " ";
}
for (j = 1; j < i; j++) {
cout << maxVal << " ";
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Remove trailing spaces by printing a space only between numbers
- Print a different padding value instead of always printing
maxVal - Right-align the rows by printing leading spaces before each line
- Convert the logic into a reusable function for other patterns
- Use
setwfor aligned output when numbers have multiple digits
Avoid
- Using
endlinside loops (unnecessary flushing) - Forgetting the second inner loop (row widths won’t match)
- Using non-positive values without validation
- Mixing row and column responsibilities between loops
Key Takeaways
The outer loop controls the starting number in each row.
The first inner loop prints from i up to maxVal.
The second inner loop fills the remaining positions with maxVal.
This keeps every row the same width, which is common in matrix-like patterns.
❓ Frequently Asked Questions
maxVal and then pads with maxVal until the row reaches the same width.maxVal to a larger number or read it from user input.Explore More C++ Number Patterns!
Fixed-width patterns are great practice for nested loops and padding logic.
Many pattern problems use a second loop just to print padding (spaces or repeated numbers) so every row has the same width.
12 people found this page helpful
