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

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 base^{exponent}. It’s worth noting that the parameters to pow() are doubles, so it can handle non-integer exponents.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <cmath> // needed for pow() #include <iostream> int main() { std::cout << "Enter the base: "; double base; std::cin >> base; std::cout << "Enter the exponent: "; double exp; std::cin >> exp; std::cout << base << "^" << exp << " = " << pow(base, exp) << "\n"; return 0; } |

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

#include<iostream>

using namespace std;

main ()

{

char gender;

float Bodweight,Wrist,Waist,Hip,Forearm,A1,A2,A3,A4,A5,B2,B,Bodfat,Bodfatp;

cout<<"Know your body fat"<<endl;

cout<<"M - Male."<<endl;

cout<<"F - Female."<<endl;

cout<<"Choose your gender:";

cin>>gender;

{

if ((gender=='F')||(gender=='f'))

{

cout<<"Enter your body weight:";

cin>>Bodweight;

cout<<"Enter your wrist measurement:";

cin>>Wrist;

cout<<"Enter your waist measurement:";

cin>>Waist;

cout<<"Enter your hip measurement:";

cin>>Hip;

cout<<"Enter your forearm measurement:";

cin>>Forearm;

A1=(Bodweight*0.732)+8.987;

A2=Wrist/3.140;

A3=Waist*0.517;

A4=Hip*0.249;

A5=Forearm*0.434;

B=A1+A2-A3-A4+A5;

Bodfat=Bodweight-B;

Bodfatp=(Bodfat*100)/Bodweight;

cout<<"Your body fat is:"<<Bodfatp;

}

}

if((gender=='M')||(gender=='m'))

{

cout<<"Enter your body weight:";

cin>>Bodweight;

cout<<"Enter your wrist measurement:";

cin>>Wrist;

A1=(Bodweight*1.082)+94.42;

A2=Wrist*4.15;

B2=A1-A2;

Bodfatp=(B2*100)/Bodweight;

cout<<"Your body fat is:"<<Bodfatp;

}

else

{cout<<"Not in the code";}

return 0;

}

its to nice bro . :)) Have Fun ! 😀

Wow! Quiz 1 was a doozy!

You really have to pay close attention to precedence and associative rules!

Even if you use parenthesis this one was hard to figure out.

I got it wrong, but Thank You for explaining this one in detail and giving us the precedence chart you put up earlier.

So is the first number within the parenthesis of pow always the base and is the second number always the exponent?

Yes.

Hi Alex

In your examples you use:

Can be changed to:

?

Either way is fine. '\n' is likely slightly more efficient than "\n" but not enough to worry about.

Hi Alex and thanks for the great tutorials. Although i have a question. I don't get it. truncate up or down or towards 0.In C++11 who i am interested whats is the correct answer?

-5 / 2 != 5 / (-2) ?

-5 / 2 == (-1)* (5 / 2) ???? = -1???

5 / (-2) == (-2) + (+2) + (+2) + (+2) = 4??? and remainder 1???

I am a bit confused....

I've updated the wording in the lesson to try and make this more clear. In C++11, integer division always truncates towards 0 (or put more simply, the fractional component is dropped).

In normal math, -5 / 2 would be -2.5, but C++11 drops the fractional component for integer division, so you get -2.

bool isEven(int x)

{

return (x % 2) == 0;

}

Hi Alex.I think writing funtion like this is short but is it good because it is may be complicate to comprehend when we read it again .Thank you so much

Is this okay-

I wrote a version of the number printing program that lines them all up nicely, just for fun.

Is there a way I could've done what I did more optimally?

Here's a stretch yourself solution ...

1) Your main should have a return statement

2) here's a redo of your printNumbers - need to add this one header <iomanip>

3) "++i" is in the next chapter 😉

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

Looks like lime cat's lime's I/O buffer got empty again, or something. Seriously, that thing needs an upgrade.

I think it must be on a little too tightly, restrict...ing the bloo...d to my.... *thump*

I've updated the section slightly to indicate that this behavior has been changed in C++11. In C++11, integer division always rounds toward 0, and a % b always takes the sign of a. So in both cases, the behavior is now well-defined.

Greetings,

Can you explain this a bit more please?

If I divide -5 by 2 the answer should be -2 1/2 or -2.5 or -2r1. I don't see how a compiler could get a remainder of 2 and much less 3.

Lastly, in mathmatics I was taught that it doesn't matter where the - sign was at. If there were an even number, the result was positve, if an odd then the result was negative. Thus -5/2 is the same answer as 5/-2. Taking the sign of a could very well give me a wrong answer in the second case!

Any clarification would help.

Thanks very much for this site. I lightly programmed in C/C++ many years ago, but I haven't been doing anything with C/C++ in the last 4 years. I was helping a friend working on a project where he is trying to use the new C++11 and we stumbled onto the site. I started at the beginning just to see if anything jumped out at me. It is amazing how much I have apparently forgotten...This is amazing!

> If I divide -5 by 2 the answer should be -2 1/2 or -2.5 or -2r1. I don’t see how a compiler could get a remainder of 2 and much less 3

I think you misinterpreted the statement, "For example, -5 / 2 can evaluate to either -3 or -2, depending on whether the compiler rounds down or rounds toward 0". This statement is talking about integer division, not using the modulus operator.

For more information about why a % b takes the sign of a in C++11, see this thread. I hope you like mathematical proofs. 🙂

"A warning about integer division and modulus with negative numbers

If either or both operands of integer division are negative, the compiler is free to truncate up or down! Most modern compilers round towards 0. For example, -5 / 2 can evaluate to either -3 or -2, depending on whether the compiler rounds down or rounds toward 0.

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

If this is the case, then how should I divide two integers if one or more of the operands are negative?

Hey i ran this program and i got the answer, i just found it weird that i barely used the main() function.

#include "stdafx.h"

#include<iostream>

#include<iomanip>

int Even()

{

using namespace std;

bool even(true), odd(false);

int x;

cout<<"type number to check"<<'n';

cin>>x;

cout<<boolalpha;

if(x%2==0)

cout<<even<<'n';

else

cout<<odd<<'n';

return 0;

}

int main()

{

Even();

return 0;

}

Ugh this one was rough. Not doing the function in #2, but actually trying to get it to read the output since I'd forgotten how booleans are called in a really weird way compared to integers.

I'd been trying to get it to read the output as true or false, and then later trying to force it to register as an integer of 1 or 0. Eventually went back to chapter 2.6 to see what I was doing wrong and discovered that feeding a boolean output into an if/then/else statement requires only stating you want to use a boolean at all, rather than defining it.

It kind of makes sense when thinking about it, since the structure of an if statement assumes true for the top statement and false for the else statement, it was just surprising that I couldn't manually tell it "if bool = true" like would be normal with an integer.

The 2.6 example is:

bool b(true);

if (b)

cout << "b is true" << endl;

else

cout << "b is false" << endl;

I kept trying to get it to do essentially the following:

if b = true

cout << "b is true" << endl;

else

cout << "b is false" << endl;

It makes sense now that I'm thinking about it, just reaaaaally weird that it won't accept the long form we've been using with integers at all, and only accepts the shorthand form for booleans. I know it's more efficient, I just hate the lack of consistency. Oh well, I'll live. =P

You can do an explicit comparison with a boolean within an if statement. You're just using the wrong operator to try to do that. Instead of the assignment operator (=), you need to use the comparison operator (==).

The correct form is:

It turns out that "b==true" is the same as "b":

So it's easier just to use "b" than "b==true".

Oh crap, thanks. I'd been trying to use the == originally at first, but had phrased it entirely wrong. When I tried re-writing it I'd changed it to just =, oops.

Still, thanks for the correction. I'll eventually memorize all these little rules somehow! ...No I won't. I still can't even spell very well in English, despite being an author and teaching creative writing classes. You'd think there would be some translation of skill there, but nupe.

Fortunately I've already started a cheat sheet for C++ of the things that I constantly forget for quick reference when things break and I can't figure out why. =P I just hope I'm not the only one who has to rely on cheat sheets religiously. XD

int isEven()

{

cout << "Please input a number to check: ";

cin >> nNumber;

if (nNumber % 2 == 0)

cout << "That number is even!\n";

else

cout << "That number is not even!\n";

return 0;

}

I didn't use the bool data type... didn't even think about it when I wrote the code >_> This works though lol.

I know that a separate function is supposed to be used for #2, but it really is as simple as

#include "stdafx.h"

#include

int main()

{

using namespace std;

cout <> x;

if (x % 2 == 0)

cout << "Yup, " << x << " is even!\n";

else

cout << "Sorry, " << x << " is odd.\n";

}

Try it out. Works perfectly.

Are there operators for percents, powers, and roots?

Unfortunately I can't make a program which solves quadratic equations without square roots or powers because the quadratic formula uses a square root. bummer

bacia - it's pretty easy to formulate best guesses on square roots. It has to do with averaging the quotients and guesses. Here's a mathematical example.

Find sqrt(9):

Guess1: 1 9/1 = 9

Average1: (9+1)/2 = 5

Guess2: 5 9/5 = 1.8

Average2: (5+1.8)/2 = 3.4

Guess3: 3.4 9/3.4 = 2.647

Average3: (2.647+3.4)/2 = 3.0235

Guess4: 3.0235 9/3.0235 = 2.977

Average4: (3.0235+2.977)/2 = 3.00025

As you can see the answer for principal roots by this method aren't as clean as they can be. But this process can be done on a computer with a high degree of precision after only a few iterations. Pretty much all you will need is a for or while loop (or recursive procedure), and the + and / operators.

use the math library,u will have to include it first

Here's my attempt at the even/odd program. Works pretty well. Side effects may include nausea, vomiting, heartburn, burning urination, and the desire to consider Rick Perry a valid presidential candidate. Ask your doctor if RobP's solution is right for you.

// Workbench.cpp : Space to test snippets or programs that don't need to be saved.

#include "stdafx.h"

#include

int main()

{

using namespace std;

int x;

cout << "Enter a number:" <> x;

if (x % 2 == 0)

cout << "You entered " << x << " which is even." << endl;

else cout << "You entered " << x << " which is odd." << endl;

return 0;

} // end of main()

Just an aside.

I'm using Code::Blocks and I try out many of the examples of code offered up by contributors (excellent stuff - teaches me loads of what not to do . . . ;-)) and examples in the tutorials.

I noticed that the terminal window says "Process returned 0 execution time : 3.102 s(or what ever)" Yet the program seems to be instant (certainly not X seconds) . . . Just curious.

Prince of Darkness

Me + Electrickery = Smoke 😉

I'm using Code::Blocks, and if I run my program from the last chapter's quiz and enter 0 as the second number (named dY in the example answer) and choose the division sign (/), it doesn't crash. Rather, it tells me the answer is "Infinity".

I'm not sure if that's compiler-specific or what, but I figured it was worth noting.

I'm using this tutorial to teach myself c++. So far it's been pretty good. I have a question about arithmetic operators in regard to powers. How does one square or cube or pentuple a number without actually mulitplying the number that many times? In other programing languages one can use the ^ symbol to indicate "raised to the power of" so that a number square could be represented as x^2 and a pentupled number can be represented as x^5.

Use the pow() function. I've updated the lesson to talk about pow().

Here's the briefest answer to #2 I could come up with:

Simplified version of the code

I got this on first try and it worked.

When i tried to compile the program that you made for question 2, it would not compile, there was a problem when it was linking, it said:" 1 unresolved externals"

First and foremost thank you so much for the tutorial. I have been wanting to get back into C++ for a long time, it has been ten years since I coded. Your tutorials have helped me get back into it. As for question number two on the quiz, I probably wrote a lot more than I had to for getting the job done, but I understand it.

In your code, I presumed your casting was done to prevent errors, which occurs when a character is enetered when we ask for integer.

It generally crashed out programs... and I never knew how to get around it...

so, a little help in this program would be appreciated.

Is there anything wrong with a function like this? Other than if 0 is entered?

There are often many ways to solve the same problem. As long as it produces the correct solution, it isn't "wrong".

Ok, figured it out, adjusted the main cout based on the IsEven condition.

Working on exercise 2), I first tried the code below. It compiled but when run, the command prompt only displayed: "Press any key to continue..." Shouldn't it have displayed a "1" since it did return as true?int main()

{

using namespace std;

bool IsEven(int x);

int x = 4;

if (x % 2 == 0)

return true;

else

return false;

return 0;

}

I experimented a bit a finally got the code below to work:int main()

{

using namespace std;

bool IsEven(int x);

int x = 4;

if (x % 2 == 0)

cout < < "My name is Even Steven" << endl; else cout << "My name is NOT Even Steven" << endl; return 0; }

This time, the output was "My name is Even Steven", showing that 4 was an even integer.

Why would it not output a 1 for the true condition in the top code?

The return value of main is passed back to whomever launched your program (either another program, or the operating system). What happens with this value is up to the caller. If you want this value to print out, you should print it before you return it.