1
$\begingroup$

I'm a rookie in the loops. I would like to use a While loop to get a solution like using a Do loop.

Do[Print["a[", i, ",", j, "]=", If[j != 4, i + j, -100]], {i, 1, 4}, {j, 2, 6, 2}]
a[1,2]=3
a[1,4]=-100
a[1,6]=7
a[2,2]=4
a[2,4]=-100
a[2,6]=8
a[3,2]=5
a[3,4]=-100
a[3,6]=9
a[4,2]=6
a[4,4]=-100
a[4,6]=10

I have tried to do something like this but I am not getting the correct result.

i = 1;
j = 1;
While[{{i < 4, j < 7} Print["a[", i, ",", j, "]=", 
  If[j != 4, i + j, -100]]}; {{i++}, {j = j + 2}}]
$\endgroup$
1
  • $\begingroup$ Your code has serious issues, you already addressed the imaginary unit, but there's this: 1) {{i < 4, j < 7} Print[...] you're missing a comma after the } and before Print, 2) what's with all the {...} going on in the last line? You should only use braces for lists and list forms not as parentheses. $\endgroup$
    – flinty
    Commented Apr 24, 2021 at 18:14

1 Answer 1

1
$\begingroup$

This produces the same result as your Do loop.

i = 1;
While[i <= 4,
 j = 2;
 While[j < 7,
  Print["a[", i, ",", j, "]=", If[j != 4, i + j, -100]];
  j = j + 2]; i++]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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