Mathematica Lab 5

MATH 220E Spring 2025

Loops and their usefulness

In this Mathematica notebook you will learn how to create For loops. In the next assignment you will use loops to help visualize the span of a set of vectors.

A computer is very good at performing a task over and over again. Mathematica provides three different “loop” constructs: For, Do, and While. We’ll concentrate on For loops, but you’re welcome to investigate the others!

To write a For loop, you have to specify four pieces of information:

Start: usually this initializes a counter variable

Test: a condition that determines when the loop stops

Increment: increase (or decrease) the counter variable

Procedure: what the loop should actually do

Here is an example For loop. Run it for yourself and observe its output.

For[i=1,i≤5,i+=1,Print[i]]

This for loop starts by initializing i=1. It repeats as long as the test condition i≤5 is true, incrementing i by 1 each time. Each time the loop repeats, it runs the procedure that prints the current value of i.

Note that to type the ≤ symbol in a code cell, simply type < followed by = and Mathematica will automatically convert it to ≤.

If you want a short (4 min) tutorial on For loops, watch the following video: https://www.youtube.com/watch?v=UpkcScYeQTc

Problem 1

Write a For loop that prints the numbers 2 through 10. (Do your exercises in a new notebook.)

Problem 2

Now change the increment of your loop so that only the even numbers 2 through 10 are printed.

For loops in functions

Next we’ll put a For loop within a function. We’ll define a function that takes as input a vector of arbitrary length and prints its entries. Don’t worry: details on the actual code will be given further below. We will name the function printVectorEntries, since that is what we want the function to do.

printVectorEntries[v_]:=Module[{i,n} (* local variables *),
(* store the length of v as n *)
n=Length[v];

(* here is our loop *) 
For[i=1,i≤n,i+=1,Print[v[[i]]]]
]

Here, we define a vector and call the function we just defined.

x={3,1,4,1,5,9,2,6};
printVectorEntries[x]

Now let’s go through the different parts of the printVectorEntries function. Make sure your Mathematica window is big enough to see the function and these notes.

printVectorEntries[v_]:=   Specifies the name of the function, similar to what we’ve seen in function definitions before.

Module[{i,n}, ...]   Tells Mathematica that we are defining a block of code (called a module), and the letters i and n will be used as variables within this code.

n=Length[v];   This assigns the length (number of components) of the vector v to the variable n. We will use n to tell the loop when to stop. The semicolon tells Mathematica that we are about to give it another statement within this module.

For[i=1, i≤n, i+=1, Print[v[[i]] ] ]   This is the loop that causes Mathematica to print each entry of vector v, starting with the 1st and ending with the nth (the last).

Lastly, you can see that the different parts of the function are on different lines. You don’t have to do this, but helps make your code more readable and easier to understand.

Problem 3

What part of the For loop do you think must be changed if you want to print all but the last entry of a vector? Define a new function called printSomeVectorEntries that does this and apply it to the vector x. (This should continue to be in your other notebook.)

Problem 4

What part of the For loop do you think must be changed if you want to print all but the first entry of a vector? Define a new function called printAFewVectorEntries that does this and apply it to the vector x.

Problem 5

What part of the For loop do you think must be changed if you want to print every other entry of a vector, starting with the first? Define a new function called printEveryOtherVectorEntry that does this and apply it to the vector x. If you’ve done this correctly, you should see 3 4 5 2 printed (in vertical form).

Another function

Next we’ll use a For loop to determine whether a particular number is equal to one of the vector entries.

The loop structure in the following code is similar to what we saw above. However, note the use of the shorthand i++, which does the same thing as i=i+1.  This is the standard way of incrementing by 1.

checkVectorEntry[k_,v_]:=Module[{i,n},
n=Length[v];

(* here is a loop that contains an if statement *) 
For[i=1,i≤n,i++,
If[v[[i]]==k,Print["Entry ",i," is ",k]]
]
]

Try out this new function:

checkVectorEntry[3,x]

checkVectorEntry[1,x]

The function checkVectorEntry contains an If statement. Let’s look at this in detail. In this function, every iteration of the loop should compare one entry in the vector v to a specified value k. The If statement performs this comparison.

The statement If[ v[[i]]==k, Print[“Entry ”, i, “ is ”, k] ] first checks to see if the entry v[[i]] equals the value k that we provided. (Recall that the double equals sign tests a comparison.) If this condition is true (that v[[i]] equals k), then the specified text is printed. If the condition is false, then nothing happens.

If we wanted something to happen when the condition is false, we simply add it to the If statement, as in the function below. Do you see where we told the function to print English words according to whether the comparison is true or false?

checkVectorEntry2[k_,v_]:=Module[{i,n},
n=Length[v];

(* here is another loop containing an if statement *) 
For[i=1,i≤n,i++,
If[v[[i]]==k,Print["Entry ",i," is ",k], Print["Entry ",i," is not ",k]]
]
]

Try it out:

checkVectorEntry2[3,x]

checkVectorEntry2[1,x]

Problem 6

Change the function checkVectorEntry so that it checks whether an entry is equal to 2k. Call the new function checkDoubleEntry and make sure you change the Print statement too. Apply your new function a couple of times. (If you’ve done this correctly, checkDoubleEntry[3,x] should something like “Entry 8 is 6” or “Entry 8 is 2 times 3.”)

Nested loops

A nested loop is a loop inside of a loop.

Let’s look at an example. The following function is similar to our printVectorEntries function, but now takes a matrix (of arbitrary size) as an input and prints its entries.  A few things to note:

Dimensions[M] gives the size of a matrix in the form {rows,columns}, so Dimensions[M][[1]] picks off the first entry, which is the number of rows.

The nested For loop comes in the form For[start of loop, loop test, loop increment, the 2nd For loop ]. In the function below, I’ve typed one For loop under the other, and Mathematica automatically indents the inner loop.

If you type multiple statements within a structure such as a loop or a module, they must be separated by semicolons. In the following code, we have three statements within the module: two statements sets the values of r and c, and the nested For loop is a statement.

printMatrixEntries[M_]:=Module[{i,j,r,c},
r=Dimensions[M][[1]];
c=Dimensions[M][[2]];

(* here is a nested for loop *) 
For[i=1,i≤r,i++,
For[j=1,j≤c,j++,
Print[M[[i,j]]]
]
]
]

Now we’ll define a matrix and call this new function.

A={{3,1,4,1,5},{9,2,6,5,3},{5,8,9,7,9},{3,2,3,8,4}};
MatrixForm[A]
printMatrixEntries[A]

Problem 7

Using nested For loops, write a function called checkMatrixEntries that takes a number and a matrix as inputs, and checks whether the number is in the matrix. You will need to combine the ideas from the functions checkVectorEntry and printMatrixEntries. Make sure you change the Print statement so that it says something like “Entry 1-1 is 3” in the end. (If you’ve done this correctly, checkMatrixEntries[3, A] should produce “Entry 1-1 is 3, Entry 2-5 is 3, Entry 4-1 is 3, Entry 4-3 is 3, or similar phrasing, in vertical form.)