easy
0 views
Function printNPattern – CTS PATTERN
Print a descending staircase pattern of a given number N
Understand the Problem
Problem Statement
Implement the function printNPattern(int N) that accepts an integer N as input and prints a descending staircase pattern using the number N.
The pattern should have N rows, where the first row contains N copies of the number N separated by spaces, the second row contains (N-1) copies, and so on, until the last row contains just one copy of N.
Constraints
- 1 ≤ N ≤ 100 (the number of rows and starting value)
- N is a positive integer
- Each row should contain the appropriate number of N's separated by spaces
- Each row should end with a newline character
Examples
Example 1
Input
5Output
5 5 5 5 5
5 5 5 5
5 5 5
5 5
5Explanation
For N=5, the first row has 5 copies of 5, the second row has 4 copies, and so on until the last row has just 1 copy.
Example 2
Input
4Output
4 4 4 4
4 4 4
4 4
4Explanation
For N=4, the pattern has 4 rows with decreasing numbers of 4's: 4, 3, 2, and 1 copies respectively.
Solution
void printNPattern(int N){
for(int i=0;i<=N-1;i++){
for(int j=0;j<N-i-1;j++){
printf("%d ",N);
}
printf("%d\n",N);
}
}Time:O(N²)
Space:O(1)
Approach:
The C solution uses a nested loop structure:
- Outer loop (i): Runs from 0 to N-1, representing each row
- Inner loop (j): Runs from 0 to N-i-2, printing spaces between numbers
- First printf: Prints N followed by a space for all but the last number in each row
- Second printf: Prints the final N in each row without a trailing space, followed by a newline
This ensures proper formatting without extra spaces at the end of lines.
Visual Explanation
Loading diagram...