Here is my final code for Programming Assignment 2.