7 The sums behind the screen

 

This chapter covers

  • How computers perform arithmetic
  • Building larger programs from small parts
  • Processing computer data such as lists

Almost everything discussed in this book—images, typefaces, encoding, laying out paragraphs—involves computer arithmetic in some form. In this chapter, we take a step back and try to answer a more fundamental question: How do computers calculate and programmers program? In this chapter, we’ll look at the mathematics behind simple calculations, including arithmetic operations, functions, and data structures such as lists.

7.1 Simple calculations

How do we calculate the answer to 1+2×3? In our heads perhaps or on paper. But how do we decide which operation to do first (the + or the ×)? Well, in mathematics, we have the convention that, in this situation, the multiplication goes first. So we may work as follows:

Something like 1+2×3 is an example of a mathematical expression. (We have underlined the part of the expression being worked on at each stage.) Rewriting it stage by stage, making it smaller each time until we reach a final answer, is called evaluating the expression. The result is a value, which is an expression that can be reduced no further: 7 is just 7. We could rewrite it as 3+4 or 1+1+5, of course, but we like each subsequent expression to be simpler than the last. Computer programs often involve these kinds of expressions, and indeed in some programming languages, the whole program is just one big expression.

7.2 More general computation

7.3 More operators

7.4 A larger function

7.5 A second task

7.6 Lists

7.7 Sorting a list

7.8 Problems

7.9 Summary