Table of contents
1.
Introduction
2.
Problem Statement
3.
Approach: Iteration
3.1.
Code
3.2.
Complexity Analysis
4.
Frequently Asked Questions
4.1.
Why is time complexity O(N2)?
4.2.
Can we input a negative number?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Rectangle Pattern Using Number in Ascending Order

Author Rhythm Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?
Interview Puzzles

Introduction

There are numerous problems out there that make you scratch your brains but occasionally there are some on the easier side as well. In this article, we are going to look at one such problem Rectangle Pattern Using Number in Ascending Order.

So let us move to the actual problem statement. 

Problem Statement

Given a non-negative number N as input, print its rectangular pattern. For example, if N=5, the design would be:

12345

12345

12345

12345

12345

Approach: Iteration

We can simply use two for loops to iterate over numbers and print the numbers. It is quite a naive and easy problem.

Let's See Its implementation.

Code

#include<iostream>
using namespace std;
int main()
{


    int N=5;
    for(int i=1;i<=N;i++)
    {
        for(int j=1;j<=N;j++){
            cout<<j;   
        }
    
        cout<<"\n";
    }
}
You can also try this code with Online C++ Compiler
Run Code

Output

12345
12345
12345
12345
12345

Complexity Analysis

Time Complexity: O(N2)

We are iterating over two nested for loops, and each ranges from 0 to N.

Space Complexity: O(1)

No extra space is used.

Frequently Asked Questions

Why is time complexity O(N2)?

Time complexity is O(N2) because we are iterating over two nested for loops, and each ranges from 0 to N. So when we sum, it is something like this:
=> N+N+N+N…… (N Times)
=> N*N
=> O(N2)

Can we input a negative number?

No, we cannot input negative numbers since it is a problem constraint that the number must be non-negative.

Conclusion

In this article, we have learned how to create rectangle patterns using numbers in ascending order in C++. We have given a brief idea of our problem statement of how we will approach this problem. We also explained it is working and how it will go through step by step.

Recommended Readings:


Also check out some of the Guided Paths on topics such as Interview Puzzles, Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Live masterclass