QUESTION 40 · Loop Applications
Write a C program to print a pattern whose row i contains i copies of i.
5 marksAnswer in brief
This pattern uses nested loops. Row 1 prints one 1, row 2 prints two 2s, and so on through the requested number of rows.
Algorithm
- Read the row count n and check its range.
- For each row from 1 through n, run an inner loop from 1 through row.
- Print the row number on each inner iteration, adding spaces between values.
- After each row, print a newline.
Worked example
For n = 3, the first outer iteration prints 1 once. The second prints 2 twice. The third prints 3 three times. Thus the three lines are 1, then 2 2, then 3 3 3. The inner limit changes with the current row, producing a triangle rather than a rectangle.
Output formatting
A space is printed before a value when it is not the first value in its row. This gives clear separation without a trailing space. The newline belongs after the inner loop, because the complete row must be printed before moving down.
Time complexity
The inner loop runs 1 + 2 + ... + n times. This sum is n(n + 1)/2. Its fastest-growing term is proportional to n², so time is O(n²) when each printed integer is treated as constant work. The example bounds n at 9, so each printed value has one digit. The bound also keeps the output easy to read.
Space complexity
Only n, row and col are stored, regardless of the number of output positions. Auxiliary space is O(1); output characters are not stored in a growing array.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n;
if (scanf("%d", &n) != 1 || n < 0 || n > 9) {
puts("Unsupported input"); return 1;
}
for (int row = 1; row <= n; ++row) {
for (int col = 1; col <= row; ++col) {
if (col > 1) { putchar(' '); }
printf("%d", row);
}
putchar('\n');
}
return 0;
}
Sample input and output
Input
3
Output
1
2 2
3 3 3