Exercises to help you learn to program
This page gives a number of simple programming exercises and solutions which
will help you learn to write for loops, while statements and if-else statements.
There are solutions to some of the exercises, but use them only after you have
made a good attempt to solve the exercises yourself. The point is to
introduce a minimum amount of syntax for these languages and get you solving
small programming problems. This page is not attempting to teach much
about these languages, and deliberately avoids using specialized commands in
favor of simpler but universal programming ideas. If you find
this page useful and would like to contribute additional exercises or solutions, perhaps in
other languages, please contact
To learn about Matlab and Octave, see the
tutorial page I made. To learn about R, see the
Writing for loops
- Write some lines of code that will calculate the sum 1+2+3+...+300.
The idea is to create a variable that will store the current value of the
sum. Set it to zero, then use a for loop that will run through the
numbers 1, 2, 3, ... and add each of these to the current sum. After
the for loop, output the value of the sum. Solution in
- Modify your program to sum the first N numbers, and set N equal to 1000,
10000, and 100000 to see what sum you get. Solution in
- Write some lines of code to calculate the sum 12 + 22
+32 + ... 4002.
- Write some lines of code to calculate the sum 1·2+2·3+3·4+
... + 249·250.
- Write a program to calculate 10! ("10 factorial"), which is defined to
- Write a program to calculate N! ("N factorial"), where N is a
non-negative integer. Note that 0! is defined to be 1.
- Write a program to calculate 11 + 22 + 33
+ ... + 1010. This
is not hard if your programming language allows exponentiation using ^, but
if it doesn't, it will be harder
- Write a program to calculate 1 + 1/1! + 1/2! + 1/3! + ... + 1/10!.
Display the sum after each term is added. Recognize the result?
Writing while loops
- Write some lines of code that will figure out how many terms in the sum
1+2+3+... it requires for the sum to exceed one million. The idea is
to create a variable that will store the current value of the sum and
another variable that keeps track of what number you are adding to the sum.
Use a while loop to add the current number to the sum, then increase the
current number by 1. The while loop should stop once the sum exceeds
one million, then you tell the current value of the sum. Solution in
Programs that use if-else statements
- Write a program to calculate the sum 1+2+3+...+300. Display the
total after every 20 terms by using an if statement to check if the current
number of terms is a multiple of 20. The basic idea is this: if
i/20 == round(i/20), print the sum.
Writing programs to make matrices
- Write some lines of code that use nested for loops to produce a 5 by 5 (square) matrix
0's down the main diagonal, 1's in the entries just above and below the main
diagonal, 2's above and below that, etc. The matrix should look like
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
- Modify the lines of code to produce an N by N (square) matrix with the
same description. Then, by first typing N=8; at the Matlab/Octave
command prompt, you should get a matrix that
looks like this:
0 1 2 3 4 5 6 7
1 0 1 2 3 4 5 6
2 1 0 1 2 3 4 5
3 2 1 0 1 2 3 4
4 3 2 1 0 1 2 3
5 4 3 2 1 0 1 2
6 5 4 3 2 1 0 1
7 6 5 4 3 2 1 0
Solution in Matlab/Octave |
- In Matlab/Octave, save the lines of code in a text file called matrix_maker.m.
Then, you can run these lines of code by typing matrix_maker at the
Matlab/Octave prompt. This program is called a script.
- Convert the program matrix_maker.m into a function by adding this text
to the top:
function [A] = matrix_maker(N)
Then, you can produce a matrix of the size you want simply by typing
matrix_maker(7) (if you want a 7 by 7 matrix) at the Matlab/Octave command
prompt. In case you're having trouble, here
is the program in Matlab/Octave. You can store the matrix you get by typing Z =
matrix_maker(7). Note that, internally, matrix_maker calls the matrix
A, but you are free to give it another name once matrix_maker returns it to
- Change the program to allow two inputs, matrix_maker_rect(5,7).
- Change matrix_maker_rect so that if only one input is given, it makes a
- Change matrix_maker_rect to return the sum S of all entries in the
Writing programs to investigate 3X+1
The game "3X+1" goes like this. If N is odd, multiply it by 3 and add
1. If N is even, divide it by 2. Repeat until N equals 1, if ever.
Every value of N that anyone has ever checked eventually leads to 1, but it is
an open mathematical problem (known as the Collatz conjecture) whether EVERY
value of N eventually leads to 1. It is also called 3n+1, and you can
read about it on
Wikipedia. Before you start working on these programs, take a sheet of
paper and write out what happens when you start with N=5, N=6, N=7, N=9, to get
a feel for it. For example, starting with N=6, the next number is 3, then
10, then 5, then 16, 8, 4, 2, 1 and we are done.
- Write a program ThreeX that, given an input value of N, will play the
game "3X+1" and print to the screen the values visited along the way.
Use a while loop.
- Have the program return the maximum value hit and the number of steps
taken and the maximum value hit. [m,c] = ThreeX(N); Solution in
- Write another program that runs ThreeX for N values going from 2 to 400.
List to the screen the numbers of steps taken and the maximum values.
- Plot the number of steps taken when starting at N as a function of N
using the plot command.
- Plot the maximum value attained when starting at N as a function of N.
- Plot the maximum value versus the number of steps.
- Modify ThreeX so that it returns a vector vals which lists the values
visited, from N all the way to 1. For instance , when N = 5,
- Keep track of how many times each number 1, 2, 3, ... is visited as N
goes from 2 to 400.
Flip a coin twenty times, keeping track of the individual outcomes (1 =
heads, 0 = tails). (Use the random number simulator in whatever language
you are using.)
Record several things in this sequence:
1. the number of heads observed
2. the number of trials where the running count of heads exceeds the running
count of tails
3. the number of switches in the sequence (a switch is where one changes from
heads to tails or from tails to heads)
Repeat your simulation 1000 times and construct a frequency table of each
outcome in part 1, 2, and 3.
Maximum, minimum, and sorting
- Generate a list of 100 random numbers and store them in a
- Use a for loop to go through the numbers and keep track of the minimum
and maximum values.
- Sort the list of numbers, this way. Start at A. Compare
it to A. If A > A, switch the values of the two. Now
compare A and A, and switch them if necessary. Continue through
the list this way. Then start at the beginning of the list again, and
again, until you run through the whole list without making a single switch.
The values will be in order. Record how many passes it takes through
the list to get them all sorted.
Base 7 counting
- In base 7, the digits 0 to 6 are used. A number like 125 means
1*7^2 + 2*7 + 5, just like base 10 but with 10's replaced by 7's. When
you count in base 7, you start 0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15,
16, 20, etc. Write a program that will print the first N numbers in
base 7. Note that you cannot simply use nested for loops to make each
digit go from 0 to 6, since you don't know how many digits you will need
ahead of time. Suggestion: store the digits in an array.
It's good enough to have an array with enough space for 10 digits.