easy
1 views

Function print_1_Pattern – CTS PATTERN

Print a triangular pattern of 1s with N rows where each row i contains i number of '1' characters separated by spaces.

Understand the Problem

Problem Statement

You are given a function print_1_Pattern(int N) that accepts an integer N as input. The function should print a triangular pattern of 1s with N rows. In the pattern, the first row contains one '1', the second row contains two '1's separated by spaces, the third row contains three '1's separated by spaces, and so on until the Nth row contains N '1's separated by spaces.

Example:

  • For N=3, the output should be:
    1
    1 1
    1 1 1
  • For N=6, the output should be:
    1
    1 1
    1 1 1
    1 1 1 1
    1 1 1 1 1
    1 1 1 1 1 1

Your task is to implement the logic for this function.

Constraints

  • 1 ≤ N ≤ 100 (N is a positive integer)
  • The function should print exactly the pattern as described
  • Each row should end with a newline character
  • Spaces should be placed between consecutive '1's in a row

Examples

Example 1
Input
3
Output
1
1 1
1 1 1
Explanation

For N=3, the pattern has 3 rows. Row 1 has 1 '1', row 2 has 2 '1's separated by space, and row 3 has 3 '1's separated by spaces.

Example 2
Input
6
Output
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
1 1 1 1 1 1
Explanation

For N=6, the pattern has 6 rows. Each row i contains exactly i number of '1's separated by spaces, creating a triangular pattern.

Solution

void print_1_Pattern(int N){
    for(int i=1; i<=N; i++){
        for(int j=1; j<=i; j++){
            printf("1");
            if(j < i){
                printf(" ");
            }
        }
        printf("\n");
    }
}
Time:O(N²) - The nested loops result in approximately N(N+1)/2 operations
Space:O(1) - Only using a constant amount of extra space for loop variables
Approach:

C Solution Explanation:

  1. Outer loop iterates from 1 to N (inclusive) to handle each row
  2. Inner loop iterates from 1 to i (current row number) to print '1's
  3. For each '1' printed, we check if it's not the last '1' in the row (j < i)
  4. If it's not the last '1', we print a space after it
  5. After completing each row, we print a newline character

This approach ensures proper spacing without trailing spaces at the end of each row.

Visual Explanation

Loading diagram...