The While statement

The While statement is used to evaluate a series of statements as long as
the specified condition is True. The structure of the While statement is the following.

While[ condition,
statements]

The statements are repeatedly executed while the condition holds True and the
loop is exited when the condition is False.

Consider the following function to find the first prime larger than an integer. We use
PrimeQ to test if a number is prime. The function also illustrates the use of the
Module function to define functions.


  firstprimeabove[ n_]:= Module[ {k},
                                k=n+1;
      					      While[ !PrimeQ[k], 
                                       k=k+1;
                                     ];
                                Return[k];
                                ]


  firstprimeabove[ 167]

In the While loop, we increment k as along as it is not prime. When the loop is
finished k is prime. Observe that even if the input is prime, then the function returns the
next prime. The first statement of Module is a list of the variables internal to the Module, and
are placed within braces. After that, there is a series of statements separated by semi-
colons.

Exercise: Modify the function to return the second prime above n, or more
generally, the function should take a second argument r, and return the rth prime
above n.

Up to Loops and Conditionals