Pattern problem doubt

could u pls explain the logic behind this code:

#include
#include
#include
#include
#include
using namespace std;

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
string str(n, ’ ');

for (int i = 1; i <= n; ++i) {
    str[n-i] = '#';
    cout << str << endl;
}
return 0;

}

Hello @neharika.srivastav,

To understand the logic you are required to understand the syntax of the statements that it is executing in the program:
Let’s understand with an example:

  1. suppose, n=3

  2. string str(n, ’ ');
    syntax:
    string (size_t n, char c);
    This would create a string of length n and would initialize all the characters of the string str with ’ ’ (space)

  3. Now, let’s iterate the for loop:
    for i=1:
    str[n-i]=str[3-1]=str[2]="#"
    i.e. the last character is set to “#”
    So, now the string contain 2 spaces followed by a “#”
    for i=2:
    str[n-i]=str[3-2]=str[2]="#"
    i.e. the second last character is set to “#”
    So, now the string contain 1 spaces followed by 2 “#”
    for i=3=n:
    str[n-i]=str[3-3]=str[0]="#"
    i.e. the first character is set to “#”
    So, now the string contain 3 “#”

Output:
ss#
s##
###
(s=space)

Hope, this would help.
Give a like, if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.