Odd-Length Increasing Number Pattern in C++

What You’ll Learn
How to print this number pattern in C++ using nested loops:
1, 123, 12345, 1234567, 123456789
The trick is to increase the row length by 2 each time (odd lengths: 1, 3, 5, 7, 9).
⭐ Pattern Output
For the last row ending at 9, the pattern looks like this:
1
123
12345
1234567
123456789Complete C++ Program
The outer loop increments by 2 to keep rows odd-length. The inner loop prints digits from 1 to i.
#include <iostream>
using namespace std;
int main() {
int i, j;
for (i = 1; i <= 9; i += 2) {
for (j = 1; j <= i; j++) {
cout << j;
}
cout << "\n";
}
return 0;
}🧠 How It Works
Choose odd row lengths
for (i = 1; i <= 9; i += 2) sets row lengths to 1, 3, 5, 7, and 9.
Print 1 to i
for (j = 1; j <= i; j++) prints 123...i for the current row.
New line
cout << "\\n"; moves to the next row.
Odd-length rows
By stepping i by 2, each row grows by two digits, staying odd.
Variation — User Input Version
Let the user choose the maximum odd row length (e.g., 9, 11, 13).
#include <iostream>
using namespace std;
int main() {
int maxOdd;
int i, j;
cout << "Enter the maximum odd row length: ";
cin >> maxOdd;
if (!cin || maxOdd <= 0) return 0;
if (maxOdd % 2 == 0) maxOdd--; // make it odd
if (maxOdd <= 0) return 0;
for (i = 1; i <= maxOdd; i += 2) {
for (j = 1; j <= i; j++) {
cout << j;
}
cout << "\n";
}
return 0;
}💡 Tips for Enhancement
Try These
- Add spaces for readability: print
cout << j << ' '; - Start from a different digit (e.g., 0 or 5) by printing
start + j - 1 - Print the same idea with even lengths by using
i += 2starting from 2 - Right-align by printing leading spaces before each row
- Change digits to characters to create alphabet sequences
Avoid
- Using
endlin tight loops (unnecessary flushing) - Letting
maxOddbe even (convert it to odd before looping) - Not validating user input when using
cin - Mixing up loop bounds (inner loop should run up to
i)
Key Takeaways
Increase the row length by 2 to keep it odd: 1, 3, 5, 7, 9.
The inner loop prints from 1 to the current row limit i.
This pattern is a clean nested-loop exercise for building row/column thinking.
It can be easily adapted to print spaced digits, shifted starts, or aligned output.
❓ Frequently Asked Questions
j from 1 to that limit.cout << j << ' ';. That will output 1 2 3 instead of 123.Explore More C++ Number Patterns!
Odd-length rows are a nice way to practice loop stepping (i += 2) and inner-loop bounds.
Using i += 2 is a simple technique to iterate only over odd values (1, 3, 5, …), which is handy in many pattern-printing tasks.
12 people found this page helpful
