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?

Priyanka
  • 48
  • 11
  • 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 https://stackoverflow.com/questions/717725/understanding-recursion , or perhaps https://stackoverflow.com/questions/39652812/how-do-i-write-a-loop-function-as-a-recursive-function. – Karl Knechtel Aug 13 '21 at 05: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. – cigien Aug 13 '21 at 15:50
  • Can't you just implement a software stack of call frames and iteratively generate them? – Karl Knechtel Aug 13 '21 at 19:35

1 Answers1

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