CALCULATIONS

We talked previously about programing with strings, and while understanding how strings work is an important concept, you’re likely going to find that most of your programming work involves numbers and calculations. And this is a good thing, given that computers are great at doing arithmetic and other basic math.

In String Theory, when we wrote the code:



you saw that the output was:


1+1

But, what if we didn’t want the program to output the string, but instead wanted the program to calculate the ‘1+1’ and output the result? This is accomplished by simply leaving off the quotation marks in our code, like this:



If you were to enter this code into your code window and run the program, your output would look like this, exactly what you’d be looking for:


2

Programming Operators

The most common math calculations you’ll do while programming will be addition, subtraction, multiplication and division. You’ve already seen that when doing addition in your code, you use the + sign, just like in the real world. And subtraction will use the – sign as well. But, when writing code, we use different operator signs for multiply and divide.

Here is a quick reference of the basic operator signs you will need to know (there are lots of others, but these are the most common):


Addition

+

Subtraction

-

Multiplication

*

Division

/


Let’s practice using these operators. In your code window, enter the following lines:



If you run this code, you should expect the following output:


2
3
4
5

Of course, computers can do more complicated calculations as well. For example, let’s say we wanted to calculate the number of seconds in a day? How would we do this?

Number of Seconds in a Day

To calculate the number of seconds in a day, the easiest way would be to multiply:

(# seconds in a minute) x (# minutes in an hour) x (# hours in a day)

We know that there are:

If we multiple each of those numbers, we should get the number of seconds in a day. Here is what the code would look like:



Go ahead and enter that code into your Code Window and run the program. Here is what your output should look like:


86400

There are 86,400 seconds in a day.