function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Monika A 22Monika A 22 

what is the difference between String added and not added in FOR loop?

In this both code, what the string is doing here that is blank value in the string pattern.

I am getting the following result for adding string out of the FOR loop:
*(1)
* * *(3)
* * * * * * (6)
* * * * * * * * * * (10)
* * * * * * * * * * * * * * *(15)


Integer n=5;
string pattern='';
for(Integer row=0;row<n;row++)
{
    for(Integer column=0;column<=row;column++)
    {
        pattern=pattern+' * ';
    }
    system.debug(pattern);
}                       

Result after adding string space in FOR loop:

Integer n = 5;
for(Integer row  = 0; row < n; row++) {
    String pattern = '';
     for(Integer column = 0; column <= row; column++) {
         pattern = pattern + '*  '; // or pattern+='*  ';
    }

    //print pattern here
    System.debug(pattern);
}

Result:
*
*   *
*   *   *
*   *   *   *
*   *   *   *   *

Can you make me understand this code part, as I got stuck here. what is the difference between these two codes.

Thanks!
Arun Kumar 1141Arun Kumar 1141

Hi Monika,

The main difference between the two code snippets is the scope and initialization of the `pattern` variable.

1. In the first code snippet, the `pattern` variable is declared outside the for-loop and initialized as an empty string before the loop. It is then updated with each iteration of the inner for-loop. At the end of each iteration of the outer for-loop, the current value of `pattern` is printed.

2. In the second code snippet, the `pattern` variable is declared and initialized as an empty string inside the outer for-loop. It is then updated with each iteration of the inner for-loop. At the end of each iteration of the outer for-loop, the current value of `pattern` is printed.

I hope this helps you understand the code better. Let me know if you have any further questions.
Thanks!