Like I told you in the previous chapter: your computer is basically just a big calculator. Whether you're listening to music, watching a movie, or playing a video game, your computer is really just doing math behind the scenes.
In this chapter, you'll learn how to perform most of the calculations a computer can do. We'll reuse what we just learned — variables. The whole idea is to do math with your variables: add them together, multiply them, store the result in another variable, and so on.
Even if you're not a fan of math, this chapter is absolutely essential. And let's be honest: if you can't do a simple addition, maybe programming just isn't for you just yet.
Basic Calculations
You should know that, in addition to being just a plain old calculator, your computer is a very basic one — it can only do really simple operations:
- Addition
- Subtraction
- Multiplication
- Division
- Modulo (I'll explain what that is if you don't already know)
If you want to do more advanced stuff (squares, powers, logarithms, and all that fun), you'll need to program them yourself — in other words, tell the computer exactly how to do it.
Thankfully, later in this chapter we'll look at a math library that comes with the C language, packed with pre-made functions. So no, you won't have to write them from scratch... unless you're a masochist (or a math teacher — that counts too :D )
Let's start with addition.
To add numbers, we use the + sign (no kidding, right? o_O). You need to store the result in a variable. For example, let's create an int variable called result and do a simple calculation:
int result = 0;result = 5 + 3;
You don't need to be a mental math wizard to guess that after running this, the variable result will hold the value 8. ^^
Of course, nothing shows up on screen with that code. If you want to see the result, just toss in a printf, like the pro you're becoming:
printf("5 + 3 = %d", result);
On screen, you'll get:
And that's your basic addition.
For the other operations, it's the same deal — just change the sign:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulo: %
If you've ever used the calculator on your computer, these symbols should look familiar. The minus sign is just a dash, multiplication is an asterisk, and division is the slash (the forward slash, to be precise).
These operations aren't particularly tricky — except for the last two (division and modulo). So let's dig into those a bit more.
Division
Division works just fine on a computer as long as there's no remainder. For example, 6 / 3 gives you 2, and your computer will give you exactly that. No problem so far.
But now let's try a division that has a remainder, like 5 / 2.
Now, if you think about it, 5 / 2 should be 2.5 :)
But check out this code:
int result = 0;result = 5 / 2; printf("5 / 2 = %d", result);
Output:
Uh-oh. That's a problem. We asked for 5 / 2, expected 2.5, and the computer tells us it's 2!
Well, here's what's happening: when it sees the numbers 5 and 2, your computer assumes they're integers, so it performs integer division. That means it cuts off the decimal part and only keeps the whole number (the 2).
Nope.
Try running the same code with result declared as a double, and you'll still get 2.
To get the actual correct result, you need to tell the computer to treat the numbers 5 and 2 as decimals — so write them as 5.0 and 2.0. That way, the computer does a floating-point division:
double result = 0;result = 5.0 / 2.0; printf("5 / 2 = %f", result);
Output:
There we go — that's more like it. Sure, it throws in a bunch of zeroes just for fun, but the answer is finally correct.
This behavior with integer division is super important to remember. Just know that for your computer:
10 / 3 = 3
4 / 5 = 0
If you want a decimal result, you've got to use decimal numbers:
10.0 / 3.0 = 3.33333
4.0 / 5.0 = 0.8
What's actually going on when you write something like 5 / 2 is that your computer is answering the question: “How many times does 2 go into 5?” The answer is 2 times. Same with 10 / 3 — 3 goes into 10 three times.
But wait, you ask — how do we get the remainder from a division? That's where our hero, modulo, steps in :)
The Modulo
The modulo is a math operation that gives you the remainder of a division. It might not be as well-known as the other four operations, but to your computer, it's just as basic — probably because it solves exactly the issue we just saw with integer division.
Modulo is represented with the % sign.
Here are a few examples:
14 % 3 = 2
4 % 2 = 0
So 5 % 2 gives the remainder of 5 / 2, which is 1. The computer figures out that 5 = 2 * 2 + 1, and it returns that 1.
Same with 14 % 3: 14 = 3 * 4 + 2, so the result is 2.
And 4 % 2 is clean — no remainder — so the result is 0.
That's about all there is to say about modulo. I just wanted to explain it in case it was new to you ;)
And now for the good news: we've officially covered all the basic math operations. No more math class — woohoo! 🎉
Operations with Variables
Now that you've got the five basic operations down, it'd be pretty cool to practice doing some calculations using variables.
There's nothing stopping you from doing something like:
result = number1 + number2;
This line adds the values stored in number1 and number2, and stores the result in the variable result.
And this is where things start to get really interesting :)
In fact, I've just had an idea. You're now totally ready to build a mini-calculator. Yes, really! I promise! :D
Picture this: a little program that asks the user for two numbers. You store those numbers in variables. Then, you add them together and store the result in a variable called result.
All that's left is to display the result right there on the screen — blowing the mind of the user, who never could've done the math that fast in their head.
Try coding this little program yourself — it's easy, and great practice!
The answer is just below:
int main(int argc, char *argv[]) { int result = 0, number1 = 0, number2 = 0;// Ask the user for number 1 and number 2: printf("Enter number 1: "); scanf("%d", &number1); printf("Enter number 2: "); scanf("%d", &number2);
// Do the calculation: result = number1 + number2;
// Display the result on screen: printf("%d + %d = %d\n", number1, number2, result);
return 0; }
Example output:
Enter number 1: 10 Enter number 2: 35 10 + 35 = 45
Not bad, huh? That's our first program that actually does something useful. It can add two numbers together and show the result right away :)
You can try it with any numbers (as long as you don't go beyond what an int can hold), and your computer will do the math in the blink of an eye (thank goodness — since it probably does billions of these operations every second anyway 😉).
I recommend trying the same thing with the other operations too (subtraction, multiplication...). Shouldn't be too hard — you just need to change a symbol or two ;)
You could also add a third variable and sum three numbers at once. That works just fine too:
result = number1 + number2 + number3;
Math Shortcuts
As promised, we don't have any new operations to learn here. And for good reason — we've already covered them all! ;)
It's with just these basic operations that you can build everything. That's all you need. I know, it's hard to believe — like, really? A 3D game is just adding and subtracting stuff under the hood? And yet... it's 100% true.
That said, C does give us some neat ways to shorten how we write these operations.
Because you'll often find yourself writing the same types of operations over and over again.
You'll see what I mean in a sec — let's talk about something called incrementation.
Incrementation
You'll notice pretty quickly that it's super common to add 1 to a variable. As your program runs, you'll often have variables that increase little by little, one step at a time.
Let's say we've got a variable called number
(yeah, super creative, I know ^^). How would you add 1 to this variable, even without knowing its current value?
Here's how you'd do it:
number = number + 1;
What's happening here? We're adding 1 to number
, and storing the result back into number
. So if number was 4, now it's 5. If it was 8, now it's 9. You get the idea...
But here's the thing — this kind of line comes up all the time. And since programmers are notoriously lazy (I mean, come on — typing the same variable name twice? Exhausting! ^^), they came up with a shortcut for it, called incrementation.
Here's the shorter version of that same line:
number++;
This little line does exactly the same thing. It means “add 1 to the variable number.” Just write the variable name, slap on two plus signs, and don't forget the semicolon.
This shortcut is super handy, and trust me, you'll use it a ton. Like I said, adding 1 to a variable is basically a daily activity in programming.
Decrementation
This one's the reverse of incrementation: it subtracts 1 from a variable. Even though incrementation is more common, decrementation still comes in handy now and then.
Here's the “long” way to write it:
number = number - 1;
And the shortcut version:
number--;
You probably saw that coming ^^ Instead of two pluses, it's two minuses. So if your variable was 6, it'll be 5 after this line runs.
Quick note: There's a small difference between number++
and ++number
. The first one returns the number first, then increments it. The second increments first, then returns it. This mostly matters when you're assigning values. For example:
int number_1 = 0, number_2 = 5; number_1 = number_2++;
In this case, number_1 becomes 5, and number_2 becomes 6. But if you write number_1 = ++number_2;
, both variables will end up with the value 6. Same goes for --. Outside of this context, though, you can use either style — it won't make a difference.
Other Shortcuts
There are other similar shortcuts that follow the same idea. This time, they work with all the basic operations: +, -, *, /, and %.
Once again, the goal is to avoid repeating the variable name in the same line.
So, say you want to multiply a variable by 2:
number = number * 2;
You can shorten that to:
number *= 2;
If number starts at 5, it'll be 10 after that line.
This works the same for all the other basic operations. Here's a small sample program:
int number = 2;number += 4; // number is now 6... number -= 3; // ... now it's 3 number *= 5; // ... now it's 15 number /= 3; // ... now it's 5 number %= 3; // ... now it's 2 (since 5 = 1 * 3 + 2)
(Come on, don't pout — a little mental math never hurt anyone!)
The nice thing about these shortcuts is that you can use them with any number, and for any of the base operations.
These are definitely worth remembering, especially when you find yourself writing a bunch of repetitive lines in a program :)
But if you're only going to keep one shortcut in your toolbox, make it ++ — it's by far the one you'll use the most ;)
The Math Library
In C, we have what are called standard libraries — that is, libraries that are always available for use. Think of them as the basic, go-to libraries you'll use all the time.
Libraries, as a quick reminder, are collections of ready-to-use functions. These functions were written by programmers before you came along, so you don't have to reinvent the wheel every time you write a new program. Pretty nice, huh? ^^
You've already used functions like printf
and scanf
, which come from the stdio.h library.
Well, there's another super handy library called math.h, which gives you access to tons of built-in math functions.
Truth is, the five basic operations we've seen so far don't quite cut it for everything! Sure, maybe you'll never need to calculate something like an exponential function (if you don't know what that is, either you're still a bit young or you've somehow dodged too many math classes :p). But the math library contains a bunch of functions that you will probably need sooner or later.
Take powers, for example — there's no native way to calculate them in C! So how do we calculate something as simple as a square? You could try typing 5² in your program, but your computer won't understand it — it has no idea what that means... Unless, of course, you tell it how — by bringing in the math library!
To use the math functions, you must include the following line at the top of your program:
#include <math.h>
Once that's in place, you're free to use all the goodies in the library.
And yep — you guessed it — I'm going to introduce you to them :) Now, since there are tons of functions in this library, I can't cover them all here. First, because it'd be way too much for you to take in all at once, and second, because my poor fingers would melt from over-typing by the end of the chapter. So I'll just stick to the main ones — the ones I think are the most useful.
Now, not everyone has the same background in math, so if some of these functions go over your head, don't worry. Just read along — this won't hurt your progress in any way. That said, here's a little free life advice: pay attention in math class. It might not seem like it now, but it does come in handy someday :p
1. fabs
This function returns the absolute value of a number — written as |x| in math.
The absolute value of a number is just its positive version:
- If you give it -53, it returns 53.
- If you give it 53, it still returns 53.
So it always gives you the positive version of the number you provide.
double absolute = 0, number = -27; absolute = fabs(number); // absolute will be 27
This function returns a double, so your variable should also be of type double.
There's also a similar function called abs, found in stdlib.h
. It works the same way, but only with integers (int), and it returns an int, not a double like fabs.
2. ceil
This one returns the next whole number greater than the decimal you pass in.
It's a kind of rounding — except it always rounds up.
So if you give it 14.188, it returns 15.
double up = 0, number = 46.71; up = ceil(number); // up will be 47
Just like before, this function returns a double.
3. floor
This does the opposite of ceil — it returns the greatest whole number less than your value.
If you give it 47.91, floor will return 47.
4. pow
Use this to raise a number to a certain power. You give it two values: the number itself, and the exponent you want.
Here's the format:
pow(number, exponent);
For example, “2 to the power of 3” (written 2^3 on most computers) means 2 * 2 * 2, which gives 8.
double result = 0, number = 2; result = pow(number, 3); // result will be 2^3 = 8
You can also use this to calculate squares — just use 2 as the exponent.
5. sqrt
This calculates the square root of a number. It returns a double.
double result = 0, number = 100; result = sqrt(number); // result will be 10
6. sin, cos, tan
Ah yes, the three classic trigonometric functions! They all work the same way and return a double.
Keep in mind: these functions expect the angle to be in radians.
7. asin, acos, atan
These are the arc functions: arc sine, arc cosine, and arc tangent. They also return double and behave just like their non-arc counterparts.
8. exp
This calculates the exponential of a number. Yup, it also returns a double.
9. log
This one gives you the natural logarithm of a number — also known as ln.
10. log10
And this one gives you the base-10 logarithm of a number.
Conclusion
Whew! And thank goodness I didn't cover all the other functions too. Just these ten are already plenty to keep you busy if you're looking for a challenge.
Again, if none of this made much sense to you, that's totally okay — you don't need this stuff right away. It really just depends on what kind of program you're writing. If you ever find yourself building a scientific calculator, though, you can bet you'll be using these a lot :p
Still, I'd recommend remembering a few essentials: floor
, ceil
, and pow
.
You'll likely need them at some point — even if you're not building a calculator, I promise :p
And that's a wrap!
This chapter is dedicated to all the Math teachers out there (a tough and underappreciated profession!). If you're still a student, here's one last freebie: programming is often a lot of math.
Understanding math makes coding way easier.
Of course, you're not going to be calculating exponentials and tangents every time you write code. Like I said (and I'll say it again): it depends on what you're building. If any of you plan on doing 3D programming later (which I do intend to teach — but much later in the course), you'll definitely need a bit of 3D geometry knowledge (you know... vectors and all that stuff)
Enjoyed this C / C++ course?
If you liked this lesson, you can find the book "Learn C Programing for Beginners" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete C / C++ workshop with many exclusive bonus chapters.