Lesson 2. A glorified calculator

 

After reading lesson 2, you’ll be able to

  • Teach a computer to do your math
  • Declare variables and constants
  • See how declaration and assignment differ
  • Use the standard library to generate pseudorandom numbers

Computer programs are capable of a great many things. In this lesson you’ll write programs to solve mathematical problems.

Consider this

Why write a program when you could just use a calculator?

Well, have you memorized the speed of light or how long it takes Mars to orbit the sun? Code can be saved and read later, serving as both a calculator and a reference. A program is an executable document that can be shared and modified.

2.1. Performing calculations

There are days when we think it would be nice to be younger and weigh a little less. In this regard, Mars has a lot to offer. Mars takes 687 Earth days to travel around the sun, and its weaker gravitational force means everything weighs approximately 38% of what it does on Earth.

To calculate how young and light Nathan would be on Mars, we wrote a small program, shown in listing 2.1. Go provides the same arithmetic operators as other programming languages: +, -, *, /, and % for addition, subtraction, multiplication, division, and modulus respectively.

Tip

The modulus operator (%) obtains the remainder of dividing two whole numbers (for example, 42 % 10 is 2).

2.2. Formatted print

2.3. Constants and variables

2.4. Taking a shortcut

2.5. Think of a number

Summary