Do and For loops:
The Do loop executes a series of statements for a variable in the specified
range.
The general format is
Do[ statements,
range]
As an example, suppose we wish to print all the primes less than 100 that
are
of the form 8k+1, then we write
In[65]:=
Do[ If[ PrimeQ[n] && (Mod[n,8]==1),
Print[ n]
],
{n, 3, 100,2}]
17
41
73
89
97
;[o]
17
41
73
89
97
Exercise: The condition in the If statement can be reduced to PrimeQ[n] by
modifying the range of n. Explain how to do this.
Exercise: Write a program to print primes of
the form x^2 +y^2. You can use one Do loop within another.
The For Statement
The For statement is more general than the Do loop and equivalent to the
While
statement. As a generalization of the Do it also includes a test and an
increment.
The format is
For[ init, test, increment, statements]
where init is the initialization sequence, and then the statements are
executed while
the test is true. The increment is performed after the statements are executed
and the
test is performed before the statements are executed.
In[66]:=
For[ x=1, x< 10, x++, Print[ Prime[x]] ]
2
3
5
7
11
13
17
19
23
;[o]
2
3
5
7
11
13
17
19
23
Here we used the increment operator ++ to increase the value of x by one. x++
is
equivalent to x= x+1;
Up to Loops and Conditionals