BIT102 ยท 2077 ยท 5 marks
Write a program to generate the following pattern of Integers. ``` 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 ```
Write a program to generate the following pattern of Integers.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
[5]
C ProgrammingChapter 6: Arrays and StringsPattern generation using arrays
Program to Generate Integer Pattern
Understanding the Pattern
Looking at the pattern carefully:
1
1 2 1
1 2 1 2 3 1
1 2 3 1 2 3 1 2 3 4 1
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 1
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Pattern Logic:
- Row
icontainsigroups - Each group in row
iprints numbers from1toi - Except the last group which prints
1toi(for last row) or ends with the row number
C Program
#include <stdio.h>
int main() {
int n = 5; // Number of rows
int i, j, k;
for (i = 1; i <= n; i++) {
// Print i groups of (1 to i)
for (j = 1; j <= i; j++) {
for (k = 1; k <= i; k++) {
printf("%d ", k);
}
}
printf("\n");
}
return 0;
}
Output
1
1 2 1 2
1 2 3 1 2 3 1 2 3
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Alternative Pattern (Pyramid Style)
#include <stdio.h>
int main() {
int n = 5;
int i, j, k;
for (i = 1; i <= n; i++) {
// Each row: groups from 1..1, 1..2, ..., 1..i
for (j = 1; j <= i; j++) {
for (k = 1; k <= j; k++) {
printf("%d ", k);
}
}
printf("\n");
}
return 0;
}
Output:
1
1 1 2
1 1 2 1 2 3
1 1 2 1 2 3 1 2 3 4
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Key Concepts Used
| Concept | Description |
|---|---|
| Outer loop | Controls the row number (i from 1 to n) |
| Middle loop | Controls number of groups per row (j from 1 to i) |
| Inner loop | Prints numbers 1 to i (or 1 to j) in each group |
| Nested loops | Three levels of nesting required |
Note: The exact pattern depends on interpretation of the question. Both versions use the same three-nested-loop logic which is the core concept being tested.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.