# How to store value of result in an array for a calculation inside the loop [closed]

Note: In my code I used j (ranging from 3 to 7) but I want j to be general

I tried this

i = 0;
For[j = 3, j < 10, j++,
q[[i++]] = 2 + j]
q


Error: Symbol q in part assignment does not have an immediate value

I also tried initializing q

i = 0;
q = {0, 0, 0, 0, 0, 0, 0};
For[j = 3, j < 10, j++,
q[[i++]] = 2 + j]
q


Output: 5[6, 7, 8, 9, 10, 11, 0]

I didn't understand why 5 is outside in 5[6, 7, 8, 9, 10, 11, 0].In output, q doesn't look like Table.

Ok well!! while writing this I was checking suggestions and could solve it, I tried

i = 0;
q = {};
For[j = 3, j < 10, j++,
temp = 2 + j;
AppendTo[q, temp];]
q


Is this a good way to do or are there even simple methods to code?

• q = Range[5, 11]. See here for how to use loops in Mathematica (Hint: don't.). Also see here for how to avoid common pitfalls in MMA. Also: the weirdness in your second example is caused by using i++. Try ++i instead. Sep 14, 2015 at 19:06
• Thanks for reminding the difference between post and pre increments Sep 14, 2015 at 19:10

You need to initialize i to be 1 rather than 0.

i = 1;
q = {0, 0, 0, 0, 0, 0, 0};

For[j = 3, j < 10, j++,
q[[i++]] = 2 + j];

q


This yields

{5, 6, 7, 8, 9, 10, 11}


In the step where you initialize q you could have used:

q = ConstantArray[0, 7];


However a much better approach is to use the comment from march. Use the Range function and you are done in one step.

q = Range[5,11]


• +1. Now why is i == 0 causing trouble? My favorite explanation: 86189 Sep 14, 2015 at 20:08