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.
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 |
Of these operators, the only ones that really need further explanation are division and modulus (remainder).
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 / 3 = 2 because the fraction is dropped. Note that integer division does not round. For example, 3 / 4 = 0, not 1.
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 result are undefined!
Modulus (remainer)
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 / 3 = 2 remainder 1, thus 7 % 3 = 1. 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. This can be useful when trying to do something every nth iteration.
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:
#include <iostream>
int main()
{
using namespace std;
// nCount holds the current number to print
int nCount = 1; // start at 1
// Loop continually until we pass number 100
while (nCount <= 100)
{
cout << nCount << " "; // print the current number
// if nCount is divisible by 20, print a new line
if (nCount % 20 == 0)
cout << endl;
nCount = nCount + 1; // go to next number
} // end of while
} // end of main()
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.
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 |
By now, you should already be well acquainted with the assignment operator, so no need to discuss it here. Because writing statements such as x = x + y is so common, C++ provides 5 arithmetic assignment operators for convenience. For example, instead of writing x = x + y, you can write x += y. Instead of x = x * 5, you can write x *= 5.
Quiz
1) What does the following expression evaluate to? 6 + 5 * 4 % 3
2) 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.
3) Name two things to watch out for when using integer division.
Answers
3.3 — Increment/decrement operators, and side effects
|
Index
|
3.1 — Precedence and associativity
|
3.3 — Increment/decrement operators, and side effects
Index
3.1 — Precedence and associativity
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.
#include<iostream> using namespace std; bool IsEven(int x); int main() { int y; cout<<"Enter an integer. The program will check if it is even(1) or odd(0): "; cin>>y; cout<<IsEven(y)<<endl; return 0; } bool IsEven(int x) { if(x%2==0) return true; else return false; }Ok, figured it out, adjusted the main cout based on the IsEven condition.
bool IsEven(int x) { // if x % 2 == 0, 2 divides evenly into our number // which means it must be an even number if (x % 2 == 0) return true; else return false; }int main() { using namespace std; cout < < "Enter a Number" << endl; int x; cin >> x; if (IsEven(x)) cout < < "Even integer, returned true" << endl; else cout << "odd interger, returned false" << endl; return 0; }bool isEven(int x) { return !(x&1); } int main() { int x; std::cout < < "Enter a Number: "; std::cin >> x; std::cout < < (isEven(x) ? "even" : "odd"); return 0; }I don’t understand. That uses more advanced stuff than stated so far.
I’m not sure what that means either, but I did something similar:
bool isEven(int x) { return !(x%2); }I do not know how to properly implement ‘&’, I’m just now learning C++ through this site, but you could make a function just as short without his method.
[...] 2007 Prev/Next Posts « 3.2 — Arithmetic operators | Home | 3.4 — Sizeof, comma, and arithmetic if operators » Wednesday, June 13th, [...]
[...] « Three questions that need to be answered before you start writing your game | Home | 3.2 — Arithmetic operators » Wednesday, June 13th, 2007 at 3:55 [...]
/* Program to know Number is Odd, Even OR Zero */
/* In torbo C++ , There are not bool Data-Type */
#include <iostream.h>
#include <conio.h>
void main()
{
int value;
clrscr();
cout << "n Enter the value : ";
cin >> value;
if(value == 0)
{
cout << "n You have enterd zero.";
}
else if(value % 2 == 0)
{
cout << "n You have enterd even number.";
}
else
{
cout << "n Tou have enterd odd number.";
}
getch();
}
/* End of Program */
Modulus: x-x/y*y =
I.e.: from quiz above;
20 % 3 =>
20 – ((20/3) * 3) =>
20 – ((6.6666666…..) * 3) => (but here integer division are used so:)
20 – (6 * 3) =>
20 – 18 =>
2
bool isEven(int x) { return !(x&1); }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”.
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.
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 of all, I’d like to thank you for the tutorial!
I just want to say that at the title “Modulus (remainer)” there’s a typing error, it should be “Modulus (remainder)”right? :)
Whenever I use an if statement it generated an error, then I added curly braces at the beginning and end of each if statement and it started working, do you have any idea why?
#include <iostream> int main() { using namespace std; cout << "Make 100 by adding a number to 23: "; double dX; cin >> dX; cout << "23 + " << dX << " Makes " << 23 + dX << endl; if (dX == 77) cout << "Congratulations you can do basic math." << endl; else cout << "\aoh dear, i hope you were testing the else statement..." << endl; return 0; }if the
is not bracketed, then it does not know what to check/ search for, and therefore won’t compile.
Although by now, you probably know why anyway. but a bit of practice in explaining anyway… every little helps.
I got this on first try and it worked.
#include <iostream> using namespace std; int nValue; bool IsEven() //function to find out if variable nValue entered is odd or even { if (nValue % 2 == 0) cout << "EVEN!" << endl; else cout << "ODD!" << endl; return nValue; } int main() { cout << "Enter Number: " << endl; cin >> nValue; // Input a number to find out if it is even or odd IsEven(); return 0; }Simplified version of the code
#include <iostream> #define TRUE 1 #define FALSE 0 using namespace std; int nValue; int IsEven() //function to find out if variable nValue entered is odd or even { return ((nValue%2)>0?FALSE :TRUE); } int main() { int retVal; cout << "Enter Number: " << endl; cin >> nValue; // Input a number to find out if it is even or odd retVal = IsEven(); if (retVal == TRUE) { cout << "Even Number: " << endl; } else { cout << "ODD Number: " << endl; } return 0; }Here’s the briefest answer to #2 I could come up with:
bool IsEven(int x) { return !(x % 2); }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.
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.
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 ;-)
[...] 3.2 Arithmetic operators [...]
VISIT and get all eBooks N Solutions free for download
Visit The IT Blog for eBooks N Solutions with Lots of Hacking Tricks
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()
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.
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.
Sorry, the second ‘#include’ should have said ”.
is the word io-stream blocked?
Very weird… are certain functions being blocked?
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.