Odds and Ends

The "Print" Command

Usually, Mathematica only returns output, after a command has been executed. Use the "Print" command to see output, while a command is being executed.

k=5;Print["This number is ",k,"."]

Strings are enclosed by "...", items are separated by commata.
"\t" produces tabbing, "\n" a new line.

k=2.8;Print["The Sine and Cosine of\t",k,"\tare given by\n",Sin[k],"\t",Cos[k],"."]

Procedural Programming

Mathematica also features the familiar procedural programming commands you might know from Fortran or Pascal: "Do", "If" and "While".

k=1;
Do[
	Print["This number is ",k,"."],
	{k,1,5}
]

The syntax of "If":  If[condition, do if true, do if false].

Do[
	If[k<10,
		Print["This number is ",k,"."],],

	{k,1,15,2}]

k=1;
While[k<10,Print["This number is ",k,"."];k=k+1]

An Example Using Recursion: The Factorial Function

5!

fact1[1]=1;
fact1[n_]:=n fact1[n-1]

Table[fact1[k],{k,1,10}]

Trace[fact1[6]]

fact2[1]=1;
fact2[n_]:=fact2[n]=n fact2[n-1]

Table[fact2[k],{k,1,10}]

Trace[fact2[11]]

Trace[fact2[5]]

fact3[n_]:=Product[k,{k,1,n}]

fact3[10]

fact4[n_]:=Apply[Times,Table[i,{i,1,n}]]

fact4[10]

Example: Prime Factorization

pf[n_Integer]:=(k=n;m=1;
		While[And[k!=1,k>=Sqrt[Prime[m]]],
			If[Mod[k,Prime[m]]==0,
				k=k/Prime[m];Print[Prime[m]],
				m=m+1]];)

pf[257931]

The "Module" Command

If others use your notebook, you want to hide auxiliary variables from your users; this can be done via the "Module" command. 
The syntax is a s follows: "Module[{local variable1, local variable2}, commands]"

a=5

Module[{a},a=Sqrt[2];Print[N[a]]]

a

Let's try this for the Prime Factorization Program:

pf[n_Integer]:=(k=n;m=1;
		While[And[k!=1,k>=Sqrt[Prime[m]]],
			If[Mod[k,Prime[m]]==0,
				k=k/Prime[m];Print[Prime[m]],
				m=m+1]];)

Clear[k,m]
pf[1234]

k

m

pfm[n_Integer]:=
	Module[{k=n,m=1},
		While[And[k!=1,k>=Sqrt[Prime[m]]],
			If[Mod[k,Prime[m]]==0,
				k=k/Prime[m];Print[Prime[m]],
				m=m+1]]]

Clear[k,m]
pfm[1234]

k
m

Replacement Rules

Using a replacement rule is a convenient way to extract results of a "Solve" command:

sol=Solve[2x^2-3x-7==0,x]

sol[[1]]

x=x/.sol[[1]]

Replacing x by "sol" gives you a list of the solutions:

x=x/.sol

A replacement rule can also be used for algebraic substitutions.
The next example shows how to "depress" a cubic equation:

Clear[a,x];
expr=a x^3+b x^2 +c x+d

expr=expr/.{x->y-b/(3a)}

Collect[expr,y]

Another example :

Graphics[Table[{AbsolutePointSize[10],Black,Point[{i,0}]},{i,1,10}],AspectRatio->1/10]

k=Table[RandomInteger[{0,2},{10}]]

pic=Graphics[Table[{AbsolutePointSize[10],k[[i]]/.{2->Black,1->Red,0->Blue},Point[{i,0}]},{i,1,10}],AspectRatio->1/10,PlotRange->{-1,2}]