0

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)?

Heba Sea
  • 65
  • 1
  • 5

1 Answers1

1
y = Range[5]; (* 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} *)
gwr
  • 13,452
  • 2
  • 47
  • 78