Variables and Assignment

What will be the output of the following code?

x=2;
y=x;
{x,y}

z:=x;
x=5;
{x,y,z}

Numbers

What is the difference between the following?

4/3
4./3

N[4/17,40]

N[4./17,4]

Repetition

Do[Print[{i,i^2}],{i,5,20}]

If we want to make a list, the Table function is often better than the Do loop.

squares = Table[i^2,{i,1,10}]

Note that Table returns a list, which we can assign to a variable and use in a later calculation.

squares

squares+1

Accumulators

Often, we need loops that modify some variable at each iteration. A common construct is to initialize a variable outside of a loop and update it with each iteration of the loop. A variable used this way is called an accumulator. Here is an example:

sum=0;
Do[
Print["i:",i];
sum +=i;
Print["sum:",sum]
,{i,1,10}]
sum

Use a loop with an accumulator to compute 1-(1/3)+(1/5)-(1/7)+(1/9)-...

sum=0;
Do[Print[{i,(-1)^(i+1), 2i-1}];
sum+=(-1)^(i+1)*1/(2i-1),{i,1,100}]
sum

N[sum]

math242.mlwright.org