2078 9

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 PartDecreasing PartFull Row
11(none)1
21 211 2 1
31 2 32 11 2 3 2 1
41 2 3 43 2 11 2 3 4 3 2 1
51 2 3 4 54 3 2 11 2 3 4 5 4 3 2 1

Logic Summary:

  • Outer loop controls the row number i from 1 to n
  • First inner loop prints j from 1 to i (ascending)
  • Second inner loop prints j from i-1 to 1 (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.