Exercises 3
Use your favorite editor or IDE to solve the following exercises. Afterward, compare your solutions with the ones in the solutions bundle.
For these exercises, you’ll be asked to declare one or more functions. Choose appropriate parameters, argument labels, and return values for your functions.
Include at least one function call with every function you declare, to show that you know how to call the function.
Exercise 3.1
Note
This exercise builds on Exercise 1.5.
Declare a set of functions to convert temperatures from Celsius to Fahrenheit and vice versa.
Exercise 3.2
Note
This exercise builds on Exercise 1.8.
Declare a set of functions to convert angles from degrees to radians and vice versa.
Exercise 3.3
Declare a function to convert an integer from decimal to binary. The function should return a string containing a bit pattern. For example, for an input of 13
, the function should return "1101"
.
Tip
There are several ways to build this bit pattern. The easiest approach is to start at the end. Figure out how to find the last bit, then use the same technique to find the other bits.
You only have to convert positive numbers. For negative numbers, simply add a minus sign in front of the bit pattern.
Exercise 3.4
Declare a function to convert an integer from decimal to hexadecimal. Look up how hexadecimal numbers work, then modify your solution for the previous exercise to generate a hexadecimal string.
Exercise 3.5
Note
This exercise builds on Exercise 2.7.
Declare a function to calculate Fibonacci numbers.
Exercise 3.6
Note
This exercise builds on Exercise 2.8.
Declare a function to calculate the factorial of a number.
Exercise 3.7
Reimplement your solution to Exercise 3.5 using recursion.
Exercise 3.8
Reimplement your solution to Exercise 3.6 using recursion.
Exercise 3.9
Reimplement your solution to Exercise 3.3 using recursion.