# how can i get the following figure using the for loop how can i get the following figure using the for loop.

n=5
For[i=1,i<5,i++,For[j=1,j<n,j++,A=(i+j)]]
A//MatrixForm


The code I found is above but not working.where is the mistake?

Welcome to MMA SE! What the code above does is simply repeatedly overwrite the value of A. In each iteration of the loop, it evaluates A = i + j, so the A at the end of the loop is simply i + j for the last i, j in the loop.

You could do a For loop where you initialize A to a table, and then set different parts of A, e.g. A[[i,j]] = "*". That's not advisable in Mathematica, but it would look like this:

n=6;
A = ConstantArray["", {n,n}];
For[i=1,i<=n,i++,For[j=1,j<=i,j++,A[[i,j]] = "*"]];
A // Grid


(Note an important change from the given code: we use j <= i, not j <= n.)

But it's far easier to simply use Table (or Array, for an alternative approach) to generate matrices, with a conditional statement in each entry that test if i < j:

Table[If[i < j, "", "*"], {i, 6}, {j, 6}] // Grid


Another way: you could also use LowerTriangularize on a 6 by 6 ConstantArray of "*", and replace all the resulting 0s in the upper triangle with "":

(LowerTriangularize[ConstantArray["*", {6, 6}]] /. (0 -> "")) // Grid

• i understand you very well. i am much obligated. thank you very much – hazal Apr 6 at 23:45
• @hazal no problem, glad I could help, and of course feel free to let me know if you have any questions! – thorimur Apr 6 at 23:57