1

I have been trying to search if there are other ways to print the below pattern:

Print a solid Rectange

 ####
 ####
 ####

I used the below code:

using namespace std;

int main ()
{
    int r,c;
    cout<<"Enter the number of rows and then columns:\n";
    cin>>r>>c;
    cout<<"Pattern:\n";
    for(int i=1; i<=r; i++)
    {
        for(int j=1; j<=c; j++)
        {
            cout<<"*";
        }
    cout<<"\n";
    }
    return 0;
}

My main question is that is there any way to remove the nested for loop or any way to make this code better?

Can we do a recursion on it? Is there a base case?

3
  • 1
    Every iterative problem can be converted to recursion and vice versa, although it isn't always easy. Whether or not to do so is subjective and thus off topic for Stack Overflow. If you want to understand how to write recursive algorithms generally, though, try stackoverflow.com/questions/717725/understanding-recursion , or perhaps stackoverflow.com/questions/39652812/…. Commented Aug 13, 2021 at 5:47
  • @KarlKnechtel Minor point: your statement is partially correct; every iterative problem can be expressed resursively, but the converse is not true. There are computable functions that can be expressed via recursion, but not iteration, e.g. the ackermann function. Commented Aug 13, 2021 at 15:50
  • Can't you just implement a software stack of call frames and iteratively generate them? Commented Aug 13, 2021 at 19:35

1 Answer 1

0

Normally recursion involves the use of individual stack frames, which atomize the process of each function call without stepping on the previous function call. There are problem sets where recursion is the best case solution to your problem, Ackermann function and complex mathematic functions coming to mind, however in this simple problem, what you did here is perfectly acceptable. One possible improvement I can suggest is the use of a separate Look Up Table for your rows designation if you can parameterize within which the user input is constrained. Simply put a LUT is a direct conversion of a Key-to-Value pairing, and in the dark corners of Leetcode optimization which I lurk, it is often a golden goose of improving code efficiency.
Check out this wizard: https://www.youtube.com/watch?v=HXNhEYqFo0o

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.