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 |

Hello,

First of all, thank you very much for this website and all of the information here. I am 100% new to code and programming, learning slow but still learning. I would like to know why the answer for question 2 was setup with bool? My answer was very different, thanks in advance.

#include <iostream>

int getNumber() {

std::cout << "Please enter a Value: ";

int x;

std::cin >> x;

return x;

}

void printResult(int x) {

if (x % 2 == 0)

std::cout << x << "Is an even number" << "\n";

else

std::cout << x << "Is not and even number" << "\n";

}

int main()

{

int value = getNumber();

printResult(value);

return 0;

}

It's due to the different way we structured our program.

In your solution, your printResult actually determines both whether the value is even/odd AND prints that result to the console. If you were to extend your program, there's no way to ask the program whether a number is true or false without printing to the console. You've coupled the two together.

In my solution, I wrote an independent function that returns a boolean to indicate whether an integer is even or not. This function leaves it up to the caller to determine how the result is used. This results in less coupling.

The difference may seem trivial, and in such a simple program, it kind of is. But in more complex programs, separating out what's potentially reusable with what's specific to an application or function can make huge differences in how extensible your programs are.

Hi Alex,

Thank you for your reply.

Alex,

I found a bug in this page. If you look at the end of https://www.learncpp.com/cpp-tutorial/31-precedence-and-associativity/ and the end of this page, you will note they both end with a similar discussion about handling exponents. You should probably remove the exponent discussion from this page.

Fixed. Thanks for pointing this out.

This works fine for me.

Hi Victor!

* @x should be declared inside @main

* Line 11: That's only a function prototype. You can't declare functions inside other functions. Line 12-19 are a block that will be entered no matter what. @isEven should return a bool.

If you don't understand this, have a look at the solution and make sure you understand that.

I do not understand this please help me to do it

A variable like userNum can store a value like an integer. Extend the given program below to print userNum values as indicated.

#include <iostream>

using namespace std;

int main() {

int userNum = 0;

cout << "Enter integer:" << endl;

cin >> userNum;

/* Type your code here */

return 0;

}

Enter integer:

4

You entered: 4

4 squared is 16

And 4 cubed is 64!!

Enter integer:

4

You entered: 4

4 squared is 16

And 4 cubed is 64!!

Enter another integer:

5

4 + 5 is 9

4 * 5 is 20

What have you tried? Why didn't it work? What do you need help with?

Hello Again

Is this code fine for Q2?

If this question was in some kind of test, should I be re-writing the code to create a bool function since the question specifies the function as isEven?

Edit: Apparently if you edit the message it will remove the

layout.

Hi Dan!

> Is this code fine for Q2?

* @main is missing a return value

* Line 15: Initialize your variables with uniform initialization

> If this question was in some kind of test [...]

Yes

> if you edit the message it will remove the [...]

Clientside issue. Refreshing the page fixes it.

Hi!

First of all, thank you! I decided to start to learning c++ and this website is amazing! I'm happy to turn off my AdBlock!

For the quiz #2 I figured out this solution:

I would like to know if can be ok use a void function to calculate if the number is even or not and to demand the answer to a print function?

Or do you think it's better work with return statements even if it's not completely necessary, just to leave the main as clean as possible.

PS: sorry for my english if it's not clear. I'm working to improve it!

Thank you and have a nice day!

Hi Alessandro!

The way you structured your program, the name "isEven" is misleading. If you change it to something like "printEvenness" it'd be better. I prefer Alex' solution.

Suggestions

* Move @main below your other functions to avoid forward declarations

* Line 9, 18: Use uniform initialization. See lesson 2.1

* Line 31: Don't compare booleans to true/false. Use them directly:

Thank you so much! I fix the issues and I used your suggestions :)

Thanks for reminding me to turn off my AdBlock!

These tutorials are helping me so its only fair they get the ad revenue

My solution:

Good practice or not?

Hi whiteorchid!

* @isEven is returning true, if the number is odd, you'd need to negate again, or don't negate at all. I prefer a comparison to 0 to explicitly get a bool.

* Don't include <string> when you need @std::atoi, @std::atoi is declared in <cstdlib>, also don't use "atoi", but "std::atoi".

* Line 12: You should check @argc before accessing @argv[1] and you should print a line feed.

References

@std::atoi - https://en.cppreference.com/w/cpp/string/byte/atoi

I don't want to call you out when you seem to know so much but I think either you are missing something really very obvious or I am.

n % 2 will always, without exception, produce either a 1 or a 0; 1 if the number is odd and 0 if the number is even.

This equates to 'true' and 'false' respectively, only, these are the opposite values than those we want. We need 'true' for even and 'odd' for false.

The function also knows it's outputting a boolean value so writing return !(n %2); will always return the desired boolean value, if it was odd it will return 0 and if it was even it will return 1.

Personally, I think it's a simple and elegant solution.

You're right, I'm wrong. Don't be afraid to call people out just because they seem to know more than you.

Instead of

I'd use

because I don't like implicit conversions (int to bool), but it's the same in the end.

My solution

Hi Aditi!

* Don't use "using namespace", it can lead to name collisions

* Initialize your variables with uniform initialization

@isEven can be reduced to

Hi Alex,

Having changed the code a little and taking out the bool expression thus:

it works as expected. In my opinion it is also easier to read and follow. Any objective criticism on how to tidy it further would be brilliant.

Your previous approach was better, get back to it and see the reply I wrote the that post.

Hi Alex,

my solution:

returns x is an even number whether it is or not. Any pointers on where I am wrong?

Hi Nigel!

Don't use a global variable, you can pass @x around as an argument and return value.

Line 29, 30 need to be

for Quiz 1) isn't

(20 % 3) = 666666666666667 ?

No. 20 / 3 = 6 remainder 2. Therefore 20 % 3 = 2 (the remainder).

Please improve my code teacher!

Hi Jhayar!

Line 7, 15: Initialize your variables with uniform initialization.

Line 6 and 18, 19: Inconsistent use of @std::endl and '\n'.

Line 18, 20: Unnecessary space before line break.

"isEven" sound like the name of a function that returns whether or not a given number is even, which is what the task asked you to do. The way you set up your code a name like "readAndPrintIsEven" would fit better.

Hello Teacher, I was reading one of the comments and I wondered why did you recommend not to use "using namespace", I've been using it all the way here and I want to know what is wrong about it. Thanks.

Hi Armal!

There's an example of a naming collision caused by 'using namespace' in lesson 4.3c.

Thank you nascar, I will get there eventually, so I will stop using it then :)

Dear Teacher, please let me say that I modified your program in lesson 2.6 (§ Boolean return values) according to quiz demand and created following program. Is this practice okay? Regards.

Hi Georges!

* Don't use "using namespace".

* Line 12: Initialize your variables with uniform initialization.

* Your formatting is not helpful.

Looks good otherwise, good job!

Dear nascardriver, please accept my thanks for you replied and for your helpful answer.

* Line 12: Our Teacher, teaches that we should not initialize variable when it is used just after its declaration.

* In line 6 parenthesis are not needed. Program works fine without them:

Regards.

> Our Teacher, teaches that we should not initialize variable when it is used just after its declaration.

Quoting lesson 1.3

"A good rule of thumb is to initialize your variables. This ensures that your variable will always have a consistent value, making it easier to debug if something goes wrong somewhere else.

Rule: Make sure all of your variables have known values (either through initialization or assignment)."

Your @integer variable has an undefined value until @std::cin::operator>> returns. If you're compiling with a pre C++11 compiler and extraction fails the value afterward will still be undefined.

> In line 6 [...]

This isn't what I meant, I'd still keep the parenthesis though. I meant line 15 and 16, those should be indented. If you want to you can also add curly brackets.

Dear nascardriver, please accept my many thanks for you replied and for your constructive answer.

1. My understanding is that in line 13 cin >> integer; that is just after variable "integer" declaration, it gets the value entered by user.

2. I use compiler c++ 14. Regards.

Here is my solution for question 2.

Any feedback is appreciated. :)

Lesson 3.2.cpp

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").

Thanks for replying.

Is this what you mean by using a different naming style?

That would work, yes.

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.

Hi Prabhat!

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

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?

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.

"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.

This is what I came up with...

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.

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!

-david

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.

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.

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.

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 http://www.learncpp.com/cpp-tutorial/185-stream-states-and-input-validation/.

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;

else

cout << "The number is odd." << endl;

return 0;

}

int main()

{

cout << "Enter a number: " << endl;

cin >> num;

isEven(num);

return 0;

}

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.

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?

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.

Is this correct?

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

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

Thanks!

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

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.

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.

This looks great. I don't think you need to include cmath, as you don't use anything from it.

Thank You

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.

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.

@isEven

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.

@nascardriver Hi!

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

@isEven

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.

@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

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.

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

e.g.:

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.

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.

Hey nascardriver!

Thanks!, and thx again for your advice about uninitialized variables, I'll be more careful about that

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"?)

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).

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!