3.2 — Arithmetic operators

Unary arithmetic operators

There are two unary arithmetic operators, plus (+), and minus (-). If you remember, unary operators are operators that only take one operand.

Operator Symbol Form Operation
Unary plus + +x Value of x
Unary minus - -x Negation of x

The unary plus operator returns the value of the operand. In other words, +5 = 5, and +x = x. Generally you won’t need to use this operator since it’s redundant. It was added largely to provide symmetry with the unary minus operator.

The unary minus operator returns the operand multiplied by -1. In other words, if x = 5, -x = -5.

For best effect, both of these operators should be placed immediately preceding the operand (eg. -x, not - x).

Do not confuse the unary minus operator with the binary subtraction operator, which uses the same symbol. For example, in the expression x = 5 - -3;, the first minus is the subtraction operator, and the second is the unary minus operator.

Binary arithmetic operators

There are 5 binary arithmetic operators. Binary operators are operators that take a left and right operand.

Operator Symbol Form Operation
Addition + x + y x plus y
Subtraction - x - y x minus y
Multiplication * x * y x multiplied by y
Division / x / y x divided by y
Modulus (Remainder) % x % y The remainder of x divided by y

The addition, subtraction, and multiplication operators work just like they do in real life, with no caveats.

Division and modulus (remainder) need some additional explanation.

Integer and floating point division

It is easiest to think of the division operator as having two different “modes”. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value. For example, 7 / 4 = 1 because the fraction is dropped. Note that integer division does not round.

If either or both of the operands are floating point values, the division operator performs floating point division. Floating point division returns a floating point value, and the fraction is kept. For example, 7.0 / 3 = 2.333, 7 / 3.0 = 2.333, and 7.0 / 3.0 = 2.333.

Note that trying to divide by 0 (or 0.0) will generally cause your program to crash, as the results are undefined!

Using static_cast<> to do floating point division with integers

In section 2.7 -- Chars, we showed how we could use the static_cast<> operator to cast a char to an integer so it would print correctly.

We can similarly use static_cast<> to convert an integer to a floating point number so that we can do floating point division instead of integer division. Consider the following code:

This produces the result:

int / int = 1
double / int = 1.75
int / double = 1.75
double / double = 1.75

Modulus (remainder)

The modulus operator is also informally known as the remainder operator. The modulus operator only works on integer operands, and it returns the remainder after doing integer division. For example, 7 / 4 = 1 remainder 3, thus 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4.

Modulus is very useful for testing whether a number is evenly divisible by another number: if x % y == 0, then we know that y divides evenly into x.

For example, say we wanted to write a program that printed every number from 1 to 100 with 20 numbers per line. We could use the modulus operator to determine where to do the line breaks. Even though you haven’t seen a while statement yet, the following program should be pretty comprehensible:

This results in:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

We’ll discuss while statements in a future lesson.

A warning about integer division and modulus with negative numbers prior to C++11

Prior to C++11, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, -5 / 2 can evaluate to either -3 or -2, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so -5 / 2 would equal -2). The C++11 specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, -5 % 2 can evaluate to either 1 or -1. The C++11 specification tightens this up so that a % b always resolves to the sign of a.

Arithmetic assignment operators

Operator Symbol Form Operation
Assignment = x = y Assign value y to x
Addition assignment += x += y Add y to x
Subtraction assignment -= x -= y Subtract y from x
Multiplication assignment *= x *= y Multiply x by y
Division assignment /= x /= y Divide x by y
Modulus assignment %= x %= y Put the remainder of x / y in x

Up to this point, when you’ve needed to add 5 to a variable, you’ve likely done the following:

This works, but it’s a little clunky, and takes two operators to execute.

Because writing statements such as x = x + 5 is so common, C++ provides 5 arithmetic assignment operators for convenience. Instead of writing x = x + 5, you can write x += 5. Instead of x = x * y, you can write x *= y.

Where’s the exponent operator?

Astute readers will note that there is no exponent operator. Instead, you have to use the pow() function that lives in the cmath library. pow(base, exponent) is the equivalent of baseexponent. It’s worth noting that the parameters to pow() are doubles, so it can handle non-integer exponents.

1) What does the following expression evaluate to? 6 + 5 * 4 % 3

2) Write a program that asks the user to input an integer, and tells the user whether the number is even or odd. Write a function called isEven() that returns true if an integer passed to it is even. Use the modulus operator to test whether the integer parameter is even.

Hint: You’ll need to use if statements and the comparison operator (==) for this program. See lesson 2.6 -- Boolean values and an introduction to if statements if you need a refresher on how to do this.


1) Show Solution

2) Show Solution

3.3 -- Increment/decrement operators, and side effects
3.1 -- Operator precedence and associativity

164 comments to 3.2 — Arithmetic operators

  • Alan

    Here is my solution for question 2.
    Any feedback is appreciated. 🙂

    Lesson 3.2.cpp

    • nascardriver

      Hi Alan!

      * I prefer std::int64_t from <cstdint> over 'long long', this is up to you though.
      * Line 7: Initialize your variables.
      * Line 18: @isIntegerEven should be a bool.
      * Line 18: The value gained from declaring copy-by-value parameters const is very little. If you want to you can keep doing so, but you won't see it a lot it other code.
      * Same name style for variables and functions, this can cause confusion (eg. "isEven" and "isIntegerEven").

      • Alan

        Thanks for replying.
        Is this what you mean by using a different naming style?

  • Prabhat Kumar Roy

    Dear Sir!

    Can you please help me in NOT GETTING THE EXTRA 1 IN THE OUTPUT in my following code for your question #2?

    Thank you.

    Best regards.

    • nascardriver

      Hi Prabhat!

      @isEven shouldn't print anything. It should return false/true based on the passed argument.

  • Kevin McCarthy

    So I have a question in regards to the counting to 100 code. Do we just give our own name to int count or is that a standard function. When counting to 100, is it the while command that does it?

    • Alex

      count is just a normal variable (of type int) used to hold a number between 1 and 100. You could give it a different name if you wanted.

      The while command causes subsequent code (between {} brackets) to execute until the while condition is false. In this case, that causes the code inside the {} to run 100 times.

  • nascardriver

    "Note that trying to divide by 0 (or 0.0) will generally cause your program to crash, as the results are undefined!"
    I think it's worth pointing out that this also goes for the modulus operator.

  • david s

    This is what I came up with...

    • nascardriver

      Hi David!

      Good job solving the quiz! Some suggestions:
      * Don't use 'using namespace'
      * "isEven" sounds like the name for a function that returns a boolean. A name like "printIsEven" is better fitting.
      * Line 26: Inconsistent use of initializations. Prefer uniform initialization.

      • David S

        Thank you for the response.  This site is awesome, I have been messing around for a few years with c++ but I always became  frustrated and I would walk away for awhile... until I found this site.  I’m 52 years old and don’t have a need to use code but it’s something I have always wanted to learn.  Thanks again!

  • J Gahr

    Is there a simpler, more surefire way to check and see whether the user actually entered an integer (instead of a fraction) than what I've written below? I can keep adding zeroes onto checkNthPlace's initializing value, but it isn't a perfect method.

    • nascardriver

      Hi J!

      The easiest method I can think of is flooring (Removing everything after the decimal point) the number and see if it stays the same.

      • J Gahr

        Ah, that's a neat trick I did not know about. Thanks for the informative reply! I will try to remember about initializing at point of declaration also.

    • Alex

      Nascardriver's solution is probably the most expedient one in this case. Another, more broad solution is to have the user enter a string, and then parse the string to see if it meets the requirements for a valid integer. I talk about string validation a bit in lesson

  • Chris

    My code seems simpler. I put the if else statement inside of the bool, then called the bool with the integer passed into the parameter. Can you tell me if this is good practice?

    #include <iostream>

    using namespace std;

    int num;

    bool isEven(int)
        if (num % 2 == 0)
            cout << "The number is even." << endl;
            cout << "The number is odd." << endl;
    return 0;

    int main()
        cout << "Enter a number: " << endl;
        cin >> num;
    return 0;

    • nascardriver

      Hi Chris!

      The quiz asked you to write a function that returns false/true if the number is odd/even. You're approach doesn't satisfy the task so you can't say it's simpler or more difficult, because it's too different.
      Usually, when checking if a number is even, one would do the calculation without writing a helper function (just like you did).

      I suggest you given lesson 1.4 and 1.4a another read, because you your return value and your use of parameters is wrong.

  • J Gahr

    Is this adequate? Seems simpler, since it's not a long program. I know it doesn't account for the user not entering an integer, but besides that, shouldn't this work fine?

    • Alex

      It works... Personally, I like having a separate function for checking if a number is even because it documents what we're using the modulus operator for, and it's reusable, but in such a simple program it's not that big a deal.

  • Maks

    Is this correct?

    When i wrote in main function "printIsEven(isEven(numberFromUser));" without "numberFromUser" it didnt work. I dont undertand why…

    • nascardriver

      Hi Maks!

      > When i wrote in main function "printIsEven(isEven(numberFromUser));" without "numberFromUser" it didnt work
      That's because @isEven expects an argument of type int, if you write printIsEven(isEven()) you're not supplying @isEven with an int.

      > Is this correct?
      It is, good job on that, but it can be improved

  • Adolfo Luciano

    how is this ? I did notice that your bool was way more simple. is making more simple recommended in general?

    • Alex

      I think this is a good program for a new programmer. There are certainly ways to optimize, but it's clear what it's done and well structured.

      Making things simpler is always recommended if it enhances clarity, but it's not strictly necessary.

  • Whittee

    Hi, thanks for the great tutorial so far. Could you please just review my code and highlight any areas
    that could have been done better, thanks.

  • yogesh brar

    Haven’t understood a bit of this one but I made it like this:

    If possible could you please explain a bit more about that boolean function mentioned above on the top as I am weak in bool, also there is one thing I want to ask as I was reading the comments, initializing the variable which the user inputs? Is that good? I mean why to initialize when user inputs it. I am cool with it but just curious to know.

    • nascardriver

      Hi Yogesh!

      Your code first:
      @isEven should not output any text, it should return a bool indicating whether the given number is even or not (Your first snippet).
      Line 12: Initialize your variables (We'll get to that in a second)
      Line 15: Don't indent that

      Initializing variables:
      Let's say you create an int without initializing it. If you're lucky the value of that int is 0, most likely it will be some arbitrary number. We want our program to be deterministic though, a random number ins't welcome here. When assigning a value right away this doesn't usually cause problems. But what if you forget to assign a value and it's in a function you don't test right away. Your program might run fine for the first dozen runs or so and then you start noticed weird behavior but can't pinpoint it. You'll waste a lot of time debugging on a problem that could've easily been prevented in the first place.

      The modulus operator returns the remainder of a division.
      Let's say you want to calculate 48 % 17.
      How many times does 17 fit into 48? 3 times with a remainder of 3, because 3 * 17 = 45 and 45 + 3 = 48. So 48 % 17 = 3.
      What about 18 % 3?
      3 * 6 = 18, the remainder is 0.
      What about 23 % 5?
      4 * 5 = 20, the remainder is 3, because 20 + 3 = 23.
      Examples for % 2:
      18 % 2 = 0, because (2 * 9) = 18
      19 % 2 = 1, because (2 * 9) + 1 = 19
      20 % 2 = 0, because (2 * 10) = 20
      21 % 2 = 1, because (2 * 10) + 1 = 21
      As you see, %2 will return 0 for even and 1 for odd numbers.

      • yogesh brar

        @nascardriver Hi!
        Thanks for your reply and it is perfectly clear now to initialize it. Won’t forget it in the future.

        As I read the whole function again and again, something cleared up a bit which I want to share if I am right do let me know or else do let me know too!
        The function isEven

        it will return either 0==0; or 1==0; because ((any number)%2) will be either 0 or 1. Since the function which returns x%2==0 is a boolean function it will return either 0 for true and 1 for false which simply means if(true) the function returned 0 and hence printed the even statement and if returned 1 it will be if(false) and prints the odd statement. So this value will be passed to the function inside the if loop like

        cleared, cleared, cleared.

        Thanks so much for clarifying by the way! Now things will go smooth from here. I was trying to avoid bool function but it is interesting.

        • nascardriver

          @isEven doesn't return 0 or 1, it returns false or true.
          if x % 2 is 0 it will return true, otherwise it returns false.

          Evaluation for x = 9

          "0 for true and 1 for false"
          It's the other way around, 0 = false, anything else = true.

          PS: Please edit replies instead of deleting and re-posting, the code tags will be displayed properly after reloading the page

        • yogesh brar

          Thanks a million for the query reply.
          Also about the post will take care of it. It was just b'coz of the tags thing.

  • xjuggy

    As any "int % 2" yields either 1 (odd) or 0 (even) are there any potential problems with defining the result as a boolean.


    • nascardriver

      Hi xjuggy!

      "any "int % 2" yields either 1 (odd) or 0 (even)"
      Or -1

      "are there any potential problems with defining the result as a bool."
      No, any int can be used as a bool but it's preferred to use an operator (eg. x != 0) to make it clear that you're now dealing with a bool.

  • RryanT

    • nascardriver

      Hi RryanT!
      Good job, I assume you have experience in other languages, beginners don't usually understand the ability to evaluate code as they're returning.
      Just one thing: Initialize x in line 10, uninitialized variables can cause undefined behavior that's hard to debug.

  • Weckersduffer

    I haven´t used a boolean but an int fuction. I would like to know how can I do for making my code ask me for a number infinite times, as in a loop. (Maybe with "while"?)

    • nascardriver

      Hi Weckersduffer!
      A while loop is a good idea.

      You could run into problems when the user enters a value that cannot be stored in an int. This is covered in lesson 5.10 (std::cin, extraction, and dealing with invalid text input).

  • merocom

    • nascardriver

      Hi merocom!
      First of all, your program is working, good job!
      Let's improve:

      An improved version of your program could look like this:

      You'll learn how to enhance your code even more in the upcoming lessons, keep going!

Leave a Comment

Put all code inside code tags: [code]your code here[/code]