Function Practice#
Here are some practice problems to help us understand functions.
Write a function called
swapthat takes two numbersaandband swaps their values. There is no return value.Write a function
sumthat accepts astd::vectorof numbers and returns the sum.Functions can be called recursively (i.e. the function calls itself on a smaller problem).
Let’s use recursion to write a function that computes the factorial of an integer.
Let’s rewrite our Prime numbers example to use a function called
is_prime()that takes anintand returns aboolindicated whether the input number is prime.Let’s rewrite our Homework #4 problem of creating a vector of
Pointand finding the distance from the origin to use a function that finds the distance for a singlePoint.Write a function called
linspacethat takes a minimum and maximum coordinate, \(x_\mathrm{min}\) and \(x_\mathrm{max}\), and a number of points, \(N\) and returns a vector with \(N\) points equally spaced between \(x_\mathrm{min}\) and \(x_\mathrm{max}\) (with those endpoints included).E.g.,
linspace(0, 1, 11)would return{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}.