4
$\begingroup$

enter image description here

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?

$\endgroup$
8
$\begingroup$

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
$\endgroup$
2
  • $\begingroup$ i understand you very well. i am much obligated. thank you very much $\endgroup$ – hazal Apr 6 at 23:45
  • $\begingroup$ @hazal no problem, glad I could help, and of course feel free to let me know if you have any questions! $\endgroup$ – thorimur Apr 6 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.