All lessons
LESSON 9/53Storing Information
Operators and Expressions
GOALChange a variable's value using the short forms.

Writing score = score + 5 gets tiring. C++ has shorter forms that mean the same thing: += adds and stores, and ++ adds exactly one.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int score = 10;
score = score + 5; // энгийн арга / the long way
score += 5; // ижил утгатай, богино / same thing, shorter
score++; // яг 1 нэмнэ / adds exactly 1
cout << score << endl;
int x = 1;
int y = x++; // эхлээд y-д өгнө, ДАРАА нь x өснө / y gets it first, THEN x grows
cout << x << " " << y << endl;
return 0;
}> what you see
21 2 1
//LINE BY LINE
Watch it run
int score = 10; makes the score box, and its first value is 10.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | нэмэх / add | 5 + 2 → 7 |
- | хасах / subtract | 5 - 2 → 3 |
* | үржих / multiply | 5 * 2 → 10 |
/ | хуваах / divide | 5 / 2 → 2 |
% | үлдэгдэл / remainder | 5 % 2 → 1 |
% works only on whole numbers. Writing 5.0 % 2 is a compile error.
Compound assignment
Every time you change a variable using its own value, there is a short form.
| Short form | Full form |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
x %= 3 | x = x % 3 |
int total = 0;
for (int i = 1; i <= 5; i++) {
total += i; // total = total + i
}
cout << total; // 15> what you see
15
Increment and decrement
++ adds one and -- subtracts one. It can go before the variable (prefix) or after it (postfix).
Both change the variable in the same way. The difference is what they hand back: prefix gives the new value, postfix gives the previous one.
int x { 1 };
int y;
y = ++x; // x ба y хоёулаа одоо 2
y = x++; // x нь 3 боллоо, харин y хэвээрээ 2int x { 1 };
int y;
y = --x; // x ба y хоёулаа одоо 0
y = x--; // x нь -1 боллоо, харин y хэвээрээ 0Inside for (int i = 0; i < n; i++) it makes no difference — the returned value is not used, so i++ and ++i behave identically.