0
$\begingroup$

How to do loop with parameter steps

For example

I want print numbers : 1,2,4,8,16

but I don't know how to do loop

code like this doesn't work

Do[ Print[i] , {i, 1, 10, i}]

$\endgroup$
  • 1
    $\begingroup$ Or, using Mathematica idioms (which are recommended), do Table[2^n, {n,0,9}] or 2^Range[0, 10]. $\endgroup$ – march Jan 7 at 17:12
0
$\begingroup$

Do does not support variable step. You can use For etc. instead.

Block[{i}, For[i = 1, i < 10, i += i^2, Print[i]]]

NestWhileList[# + #^2 &, 1, # <= 10 &]

By the way, your example is just Do[ Print[2^i] , {i, 0, 9}].

| improve this answer | |
$\endgroup$
  • $\begingroup$ I'm interested in parameter steps not this example $\endgroup$ – Bruce Jan 7 at 9:04
0
$\begingroup$

Define iteration step as a function of current value of iterator (simple in this particular case):

step[i_] := i

Next we can generate values of iterator with this varying step:

values = NestList[# + step[#], 1, 10]

{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}

And use this values in iteration:

Do[Print[i], {i, values}]
| improve this answer | |
$\endgroup$

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