working code for Algorithm part of assignment