Most of your programs will use numbers, and will need to perform and calculations on those numbers. Computers are ideal for doing numerical calculation -- its what they were created for. If it takes you a minute to multiply two ten digit numbers together, then an average desktop computer today is more than a trillion times faster than you.
In STRING THEORY, when we wrote the code:
and 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
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.0
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?
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:
60 seconds in a minute
60 minutes in an hour
24 hours in a day
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.