3 Control flow

 

This chapter covers

  • Using Boolean values in conditions
  • Running the same code multiple times using while and for loops
  • Deciding what code to run with an if statement
  • Looping over ranges of numbers
  • Defining functions spanning multiple lines of code
  • Implementing control flow using recursion or iteration

Control flow is what separates a computer from a mere calculator. Calculators are for computing single expressions. Computers, on the other hand, have the ability to repeat the same calculations with different inputs numerous times without human intervention. Computers can choose to perform one calculation over another based on whether or not a condition holds true.

In this chapter you will explore code examples oriented around producing mathematical tables. You will learn about tables for trigonometric functions, as such tables are well known and of historical importance. Later you will explore conditional execution to help track the growth of rabbits using a method developed by Italian mathematician Fibonacci 800 years ago.

3.1 Navigation and trigonometry

In the age of sail the use of mathematical tables became more widespread, and a need to develop ways to automate the calculation of these tables developed (navigation is based on the calculation of angles and the sides of triangles; figure 3.1). This meant calculating trigonometric functions such as sine, cosine, and tangent.

3.2 Boolean expressions

3.2.1 Compound statements

3.3 Looping

3.3.1 Flowchart

3.3.2 Making a mathematical table for the sine function

3.3.3 Range objects

3.3.4 For loops

3.4 Multiline functions

3.4.1 Implementing the sine trigonometric function

3.5 Implementing factorial

3.6 Factorial with recursion

3.7 If statements