PAT001 - Editorial

PatternsMania-Editorial

Difficulty: cakewalk

Prerequisite: Loops and basics of programming

Problem Statement

Let’s do some pattern designing, shall we? (You can’t say no xD). Here’s an interesting pattern to make. In this, you have to print from 1 to 10 as shown in the sample output but with a twist.

Hint

After each row the value of N is decreasing by 2

Short Explanation

In this problem, we have to print the pattern in such a manner that it prints all the numbers from 1 to N in such a way that after every row the value of N decreases by 2. We can achieve this by making 2 loops, the parent loop will control the number of rows and the value of N while the nested loop will focus only on printing the numbers with a space.

Detailed Explanation

To solve this first we made a while loop which is going to loop till N is greater than zero. As soon N is 0 or less it will be terminated. After every iteration, the value of N will decrease by 2. In the nested loop, we will print the numbers from 1 to the current value of N (which is decreasing by 2 after every new row) along with a space. Once the nested loop is completed we will print a new line and reduce the value of N by 2. And the while loop will start iterating again till N reaches 0 or less.

Time Complexity:

O(N^2) as we are using nested loops of size N

Space Complexity:

O(1) - no change of space during runtime

Alternate Solution:

None

Author: Sidharth Sethi - techspiritss
Tester: Ramandeep - ramandeep8421
Editorialist: Sidharth Sethi - techspiritss

Tester’s Solution:
Implementation Language: C++

#include <bits/stdc++.h> 
using namespace std;
 
void solve(){
    int n;
    cin >> n;
    assert(n >= 1 && n <= 100);

    while(n > 0){
      for(int i=1;i<=n;i++)
        cout << i <<" ";
      n -= 2;
      cout << "\n";
    }
  
}

int32_t main() {
 
    int t=1;
    for(int test=1;test<=t;test++){
      solve();
    }
}

Setter’s solution:
Implementation Language: C

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    
    while(n > 0)
    {
        for(int j = 1; j <= n; ++j)
        {
            printf("%d ", j);
        }
        printf("\n");
        n -= 2;
    }
    return 0;
}

Python Implementation:

N = int(input())

while N>0:
    for i in range(1,N+1):
        print(i, end = " ")
    
    print("")
    N-=2