Creating an array with “For” loop

I need to perform a number of operations within a For loop and store the results in an indexed array (without using the Append function) For examole (to make it simple), I need to find the square of numbers i = 1 to 5 and sore it in y[i]. In precedural languages it would look like:

   for i = 1,5,i++,
y(i)=i^2
end


To implement this in Mathematica I tried this code:

 For[i = 1, i <= 5, i++,
y[[i]] = i^2;
]


which failed. Is there a way to create such array (y)?

• Do you understand why it failed? y is not defined, so you can't access y[[i]]. Try defining y before and it works (for that, see e.g. ConstantArray). Edit My comment assumes, as you state, that you need to use For. Otherwise that's much simpler with Table. – anderstood Mar 23 '18 at 16:44
• You almost never need a For[] loop. Try y = Range^2. – J. M. is away Mar 23 '18 at 16:44
• Or lookup Table. – gwr Mar 23 '18 at 16:45
• Then you should look up Map[] or Table[] as already suggested, if you have a list of images. If you really must loop, use Do[] instead. – J. M. is away Mar 23 '18 at 17:09
• If OP is doing image processing OP should probably be using at least some of Mathematica's image processing functions: Blur, a whole host of Filters, etc. – High Performance Mark Mar 23 '18 at 20:33

y = Range; (* y needs to be predefined as anderstood pointed out *)
For[ i = 1, i <= 5, i++,
(* body *)
y[[i]] = i^2
]


If it has to be For...

y
(* {1, 4, 9, 16, 25} *)

• Thank you so much! – Heba Sea Mar 23 '18 at 16:52
• @HebaSea You are welcome. Be sure to look up the alternatives given in the comments above. For really is no fit for Mathematica. – gwr Mar 23 '18 at 16:56