Optimise code of exercise1 and 3, compleated exercise 4