The pattern is generated using nested for and while loops, with a single counter that continues increasing across all rows.
- The outer loop controls the number of rows.
- The inner loop prints the required numbers in each row while the counter continues from the previous row.
Number Pattern Illustration
For n = 5, the pattern is:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Using for Loop
The outer for loop iterates through the rows, while the inner loop prints as many numbers as the current row requires. The number variable is incremented after every print, so it is not reassigned when a new row starts.
#include <iostream>
using namespace std;
int main()
{
int rows, columns, number = 1, n = 5;
// first for loop is used to identify number of rows
for (rows = 0; rows <= n; rows++) {
// second for loop is used to identify number of
// columns and here the values will be changed
// according to the first for loop
for (columns = 0; columns < rows; columns++) {
// printing number pattern based on the number
// of columns
cout << number << " ";
// incrementing number at each column to print
// the next number
number++;
}
// print the next line for each row
cout << "\n";
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
- For each row, the inner loop runs according to the current row number:
- The number variable is incremented after every print and retains its value when the next row begins.
Using while Loop
The same pattern can be generated using nested while loops. The outer loop controls the rows, while the inner loop prints the required number of elements for each row.
#include <iostream>
using namespace std;
int main()
{
int rows = 1, columns = 0, n = 5;
// 1 value is assigned to the number
// helpful to print the number pattern
int number = 1;
// while loops check the condition and repeat
// the loop until the condition is false
while (rows <= n) {
while (columns <= rows - 1) {
// printing number to get required pattern
cout << number << " ";
// incrementing columns value
columns++;
// incrementing number value to print the next
// number
number++;
}
columns = 0;
// incrementing rows value
rows++;
cout << endl;
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
- The outer while loop processes one row at a time. For every row, the inner while loop prints the required number of elements.
- The number counter is declared only once and is continuously incremented. It is not reset when a new row starts, which produces the required continuous sequence.