**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:

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

**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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#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 return 0; } // end of main() |

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:

1 |
x = x + 5; |

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?**

You’ll note that the ^ operator (commonly used to denote exponentiation in standard mathematical nomenclature) is a Bitwise XOR operation in C++. C++ does not include an exponent operator. To do exponents in C++, #include the <cmath> header, and use the pow() function:

1 2 3 |
#include <cmath> double x = std::pow(3.0, 4.0); // 3 to the 4th power |

Note that the parameters (and return value) of pow in the above example are of type double. std::pow() assumes the base is a floating point number. Note that due to rounding errors in floating point numbers, the results of pow() may not be precise (slightly smaller or larger than what you’d expect).

If you want to do integer base, you’re best off just using your own function to do so, like this one (that uses the non-intuitive “exponentiation by squaring” algorithm for efficiency):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// note: exp must be non-negative int pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } |

Don’t worry if you don’t understand all of the parts of this function yet. Just beware of overflowing your integer result, which can happen very quickly if either argument is large.

**Quiz**

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.

**Answers**

3.3 -- Increment/decrement operators, and side effects |

Index |

3.1 -- Operator precedence and associativity |

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

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!