BIT102 ยท 2078 ยท 5 marks
Write a program to generate the following pattern of integers. ``` 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 ```
Write a program to generate the following pattern of integers.
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
[5]
C ProgrammingChapter 6: Arrays and StringsPattern generation using arrays
Quick answer
Each row i prints numbers from 1 to i, then back from i-1 to 1.
Pattern Generation Program
Pattern Analysis
Looking at the pattern carefully:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
C Program
#include <stdio.h>
int main() {
int n, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
/* Print increasing part: 1 to i */
for (j = 1; j <= i; j++) {
printf("%d ", j);
}
/* Print decreasing part: i-1 down to 1 */
for (j = i - 1; j >= 1; j--) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Output (for n = 5)
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
Step-by-Step Explanation
| Row (i) | Increasing Part | Decreasing Part | Full Row |
|---|---|---|---|
| 1 | 1 | (none) | 1 |
| 2 | 1 2 | 1 | 1 2 1 |
| 3 | 1 2 3 | 2 1 | 1 2 3 2 1 |
| 4 | 1 2 3 4 | 3 2 1 | 1 2 3 4 3 2 1 |
| 5 | 1 2 3 4 5 | 4 3 2 1 | 1 2 3 4 5 4 3 2 1 |
Logic Summary:
- Outer loop controls the row number
ifrom1ton - First inner loop prints
jfrom1toi(ascending) - Second inner loop prints
jfromi-1to1(descending) - Total numbers in row
i=2i - 1
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.