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 R directions.  For JavaScript, see the JavaScript explanation.  Octave, JavaScript, and R are free and easy to get started with. 

Writing for loops

Writing while loops

Programs that use if-else statements

Writing programs to make matrices

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.

Statistical simulation

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

Base 7 counting