Unary arithmetic operators

There are two unary arithmetic operators, plus (+), and minus (-). As a reminder, 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 minus operator returns the operand multiplied by -1. In other words, if x = 5, -x is -5.

The unary plus operator returns the value of the operand. In other words, +5 is 5, and +x is 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.

For best effect, both of these operators should be placed immediately preceding the operand (e.g. `-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 *binary 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. We’ll talk about division below, and modulus in the next lesson.

Integer and floating point division

It is easiest to think of the division operator as having two different “modes”.

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 / 4 = 1.75`

, `7 / 4.0 = 1.75`

, and `7.0 / 4.0 = 1.75`

. As with all floating point arithmetic operations, rounding errors may occur.

If both of the operands are integers, the *division operator* performs integer division instead. Integer division drops any fractions and returns an integer value. For example, `7 / 4 = 1`

because the fractional portion of the result is dropped. Similarly, `-7 / 4 = -1`

because the fraction is dropped.

Warning

Prior to C++11, integer division with a negative operand could round up or down. Thus `-5 / 3`

could result in -1 or -2. This was fixed in C++11, which always drops the fraction (rounds towards 0).

Using static_cast<> to do floating point division with integers

The above raises the question -- if we have two integers, and want to divide them without losing the fraction, how would we do so?

In lesson 4.11 -- Chars, we showed how we could use the *static_cast<>* operator to convert a char into an integer so it would print as an integer rather than a character.

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> int main() { int x{ 7 }; int y{ 4 }; std::cout << "int / int = " << x / y << '\n'; std::cout << "double / int = " << static_cast<double>(x) / y << '\n'; std::cout << "int / double = " << x / static_cast<double>(y) << '\n'; std::cout << "double / double = " << static_cast<double>(x) / static_cast<double>(y) << '\n'; return 0; } |

This produces the result:

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

The above illustrates that if either operand is a floating point number, the result will be floating point division, not integer division.

Dividing by zero

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

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { std::cout << "Enter a divisor: "; int x{}; std::cin >> x; std::cout << "12 / " << x << " = " << 12 / x << '\n'; return 0; } |

If you run the above program and enter 0, your program will either crash or terminate abnormally. Go ahead and try it, it won’t harm your computer.

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 4 to a variable, you’ve likely done the following:

1 |
x = x + 4; // add 4 to existing value of x |

This works, but it’s a little clunky, and takes two operators to execute (operator+, and operator=).

Because writing statements such as `x = x + 4`

is so common, C++ provides five arithmetic assignment operators for convenience. Instead of writing `x = x + 4`

, you can write `x += 4`

. Instead of `x = x * y`

, you can write `x *= y`

.

Thus, the above becomes:

1 |
x += 4; // add 4 to existing value of x |

5.3 -- Modulus and Exponentiation |

Index |

5.1 -- Operator precedence and associativity |

Hi! I tried to write the second exercise without bool like this

and it works for numbers with 10 digits, but for the bigger numbers it outputs only "You entered an even number". Can you please explain whats wrong with it?

If you input a number that's too large, you'll overflow integer variable x and the value won't be what you expect. If you print the value of x, you should be able to see this happening.

I guess I overcomplicated mine a bit, but I like having separate functions.

Hi; please tell me what's wrong with my writeAnswer() function. isEven evaluates correctly, but writeAnswer thinks evertything is even, even when isEven returns false. I have a feeling I'm being really dumb and not seeing something simple.

functions.h

functions.cpp

source.cpp

This will always evaluate to true. This says, "if the isEven function has an address greater than 0" (which will be always if the isEven function exists).

Here's what you wanted:

This says, "if the return value of the isEven function is true", which is what you actually wanted.

Tried this previously and got the compile error "function does not take 0 arguements".

Oh, you need to pass function isEven() an argument:

Also tried that but compiler says "identifier "x" is undefined" (using visual studio)

That's because your writeAnswer() function is missing parameter x, which should be passed in from main().

Hi Alex. Thanks for the great tutorials.

I have a few doubts.

1) In this piece of code:

You've used the same name for a function and a variable in it. Doesn't that cause a naming conflict?

2)

Here, can't we do

instead of

1) No. The local variable name shadows the function name. We discuss shadowing in chapter 4.

2) No. That does integer division on x / y and then casts the result to a double. We want to do double division, which means at least one of the operands must be a double before the division operation takes place.

Got it, thanks!

it would be less confusing if the hint in quiz #2 linked to section 2.6 instead 2.7

Agreed. Thanks for pointing this out!

After reading this multiple times, I still have no idea how the modulus (remainder) works. Could you explain it differently or post a link that explains it in depth?

EDIT:

Even though I'm not quite understanding the modulus, I managed to complete the second quiz haha :D

[code]#include

using namespace std;

bool isEven(int number)

{

if (number % 2 == 0)

return true;

else

return false;

}

int main()

{

cout <> number;

if (isEven(number))

cout << number << " is even.n";

else

cout << number << " is odd.n";

return 0;

}[code]

Modulus is just another name for the remainder left over after doing an integer division.

So, 7 / 4 = 1, because the fraction is dropped.

7 % 4 = 3, because 7 / 4 is 1, leaving a remainder of 3. That 3 is the result of the modulus.

The output was 1 when val was equal to 9.

Can you explain me how?

1/2 does integer division and results in 0 (1/2 is 0.5, but integer division drops the fractional portion, so you're left with 0). Any number to the 0th power is 1.

You probably meant to do 1.0/2.0 instead of 1/2, so you get floating point division.

Why can't we use integers in the place of chars?

To do what? I'm not clear on the context of your question.

In every case. Chars serve the same purpose as that of integers. So, why not use int.

They don't serve the same purpose.

* Chars are only 8-bits, where integers are minimum 16 bits.

* Chars print as ASCII characters, whereas integers print as numbers.

* Strings contain chars, not integers.

Well this was my first attempt at question 2, but I think I missed the point about having a function return true :P great tutorial again!

Couldn't the isEven function be simplified further?

bool isEven(int x)

{

return (x % 2);

}

It still returns the correct true/false information.

It could be simplified to the following:

Why This? Can you explain me, please!

If x is even, then x % 2 = 0, which the ! flips to a 1, which becomes boolean true.

If x is odd, then x % 2 = 1, which the ! flips to a 0, which becomes boolean false.

Hi Alex and I thanks you for your reply, but:

It seems like i the function below !(x % 2) evaluates to 1 as function return value. Consequently By default, a bool function return 0(false) while I think the opposite

Enlighten me, please!

I'm not sure I follow. !(x % 2) only evaluates to 1 if x is even.

For integer to boolean conversions, 0 becomes false, and any non-zero values becomes true.

Excuse me, I wanted to mean why compilers interpret

to

implicitly?

I'm sorry, I don't understand what you're asking.

Hi Alex, here's a code, can you tell me if the code is pretty , a good code factorized and commented if no, how do I do for ameliorating it?

main() and continueOrStop() are pretty redundant -- you could consolidate them.

I'd also put the comments on the actual functions rather than the forward declarations.

Other than that, I don't see anything particularly noteworthy.

Greetings,

Your quiz question 2 stated that we will need to use if statements in our code. However I coded this without if statements. Perhaps I misunderstood the question? The following is my code:

Your program doesn't tell the user whether the number is even or odd, it tells them 1 or 0 representing whether the number is even or odd.

But that's also fixable without using an if statement (by using the conditional operator), so yes, there is a valid solution that doesn't use "if".

I posted an answer to a question about code for this tutorial here.

I like to make loops to allow the user to decide when the program should end.

On exercises 2's answer, why?:

Why not simply?:

'%' has higher precedence than '==', it will be better practice to use without parentheses.

return x % 2 == 0 assumes both the code author the reader remembers that % has higher precedence than ==. Even though the parenthesis in this case are superfluous, they both make your intent clear and ensure you haven't misremembered the prioritization. In general, you should be optimizing your code for readability, correctness, and maintainability -- consequently, I would say it's a better practice to use the parenthesis in this case than not (there's no runtime performance penalty for using them).

I am trying to learn the c++ modulo. I was able to get the positive integers to run and compile... But whenever I try the negative divisor it doesn't compile .....

I just found your page and would post my program in a few....

Thanks and looking to learn from here as others have...

Yes, please post the code that doesn't work and then we can examine why.

I did that code "on my way", but the compiler accuses an error in lines 8 and 9.

What can it be? I never used string like data type, so... probably it's a lil mistake

ty, and sorry for my bad english. I'm not american, so english isn't mine/my (idk, but I think it's mine ahuauha) mother tongue :s

Obs: I'm using Netbeans IDE, in Ubuntu 16.04

I'm not sure which specific lines are causing errors, but just inspecting your program, a few things jump out at me:

A few thoughts here:

1) Your isEven() function is returning a string -- if it's going to return a string, it should return a std::string.

2) Your isEven() function should really be returning a boolean.

3) Also make sure you've #included the string header.

Well, I think now your tutorials are mature enough to write a book, it may not be a best seller, but you can leave your legacy in C++ history, people will quote your work, your examples, and teach with your material.

You have such a great didactic and is really easy to understand what you want to teach and very few people has that gift.

For sure it could be a struggle to do it, but never will be worthless.

I thank you for this project, is awesome and maybe you are used to people saying this, but I'm learning a lot thanks to you.

Sorry for my English it's not my native language.

Best wishes,

Thank you for your kind words. The biggest problem with books is they are expensive, and that makes them inaccessible to a large portion of the world. The great thing about this website is that it is accessible for everyone with internet (since it's ad-sponsored, something I can't do with a book)! My goal isn't to be famous or quoted -- my goal is to help others learn C++, just like others once helped me. This is my little mark on the world, and I'm proud that so many people from all countries of the world, rich or poor, have been able to visit.

Hi Alex,

Perhaps you wanted us to use the functions and everything you taught us, but in think this is the simple way to make this program,

Yes, I want to make sure you're getting used to using functions, and thinking about modularity.

Awesome you are still replying, sooo much dedication!!!

Are you writing a book?

Nope. I got asked to write a book, but I declined because I don't have enough time (I can work on this website as time permits -- no deadlines!). :)

#include "stdafx.h"

#include <iostream>

int userInput()

{

std::cout << "Enter an integer and know whether it is even or odd: ";

int integer;

std::cin >> integer;

return integer;

}

void isEven(int x)

{

if ( x % 2 == 0)

std::cout << "The entered integer is even";

else

std::cout << "The entered integer is odd";

}

int main()

{

int input = userInput();

isEven(input);

return 0;

}

Another simple way. I hope it will work fine everywhere.

Getting a hang of programming in C++ now.

Thanks Alex!

i wrote a code for the second question and it is way different from what you wrote but it works fine. i want to know your take on my code pls and thank you

Did you test this program? If so, you'd know that it doesn't work. It starts off good, getting a number from function enternum(), which is passed back to main. But that value (x) is never used. Instead, iseven() declares its own local uninitialized variable x and then uses that to try to determine even or not. That will lead to undefined results.

You need to pass the variable x in main to function iseven() as a function parameter, and have iseven() use that variable. Then your program will not only be well structured, it will actually work too. :)

I understand what you're getting at. but the first program did work.

Ihowa,

It doesn't work, I tried to compile it and gave me warnings about x not being used, Alex is right in order to work you need to pass x to iseven() function, should be like this,

Is there any reason someone shouldn't do:

Nope, nothing wrong with that.

Okay, cool! I was worried that maybe I was doing some "unethical" programming, or something. Thanks for the quick reply.

Also, thanks for this whole tutorial, it's a great resource!

Or you know

return!(x % 2);

cause you already taught us that everything !=0 bool sees as true.

Interesting. but in his example

return (x % 2) == 0;

it will only either return a zero for FALSE and a non-zero value for TRUE. did you mean add ! in case the remainder is a negative ? i dont see what else could be missing return (x % 2) == 0; looks fine.

The following two statements evaluate identically:

in your example above, you forgotten to insert "return 0"

if i compile it says error

#include <iostream>

int main()

{

// count holds the current number to print

int count = 1; // start at 1

// Loop continually until we pass number 100

while (count <= 100)

{

std::cout << count << " "; // print the current number

// if count is evenly divisible by 20, print a new line

if (count % 20 == 0)

std::cout << "\n";

count = count + 1; // go to next number

} // end of while

} // end of main()

Returning an explicit value from main is actually optional (but a good idea none-the-less). I've updated the example.

why does this ask me for an integer 4 times?

[#include "stdafx.h"

#include <iostream>

int getNumber()

{

std::cout << "enter and integer";

int x;

std::cin >> x;

return x;

}

int main()

{

getNumber();

if (((getNumber()) % 2) == 0)

std::cout << getNumber() << "is even\n";

else

std::cout << getNumber() << "is odd\n";

} ]

4 times? It should only ask 3 times. And this happens because getNumber() asks the user to enter an integer each time it is called. And you're calling it 3 times (only one of the conditional statements gets executed).

What you should do is assign the return value of getNumber() to a temporary variable, and use that variable instead of calling getNumber() again.

why can't we use in this way?

Because this does x / y first (which is an int divided by an int, which produces an integer result) and then converts the integer to a double.

oh!!!! thanks again!

My version ; still too messy but added a twist ;)

And here is a different version of your counting, C++ starts to get funny... thanks a lot for all the tutorial and really really well done quizz.

Thank you so much for these tutorials. I've tried a number of times to get my head around programming over the years. Decided to give it another go and these tutorials are fantastic!

This was my solution to question 2. More coding than was needed but works fine. Streamlining will come with experience :)

Is this acceptable? Or really, is this less efficient in any way?

Is it acceptable from what perspective? Does it work? Yes. Does it meet the quiz requirements? No. The quiz asked you to create a function named isEven() and you didn't.

The semantics of += (add assignment operator) are different in C & C++. += operator returns lvalue (locator value) in C++ but not in C. That's why following program is valid in C++ but invalid in C.

When you compile above program in C the compiler gives you following error:

[Error] lvalue required as left operand of assignment