Skip to content

Operators

Operators

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.

1
2
3
4
5
6
7
int n1 = 8;
int n2 = 3;
std::cout << n1 << " + " << n2 << ": " << n1 + n2 << '\n';
std::cout << n1 << " - " << n2 << ": " << n1 - n2 << '\n';
std::cout << n1 << " * " << n2 << ": " << n1 * n2 << '\n';
std::cout << n1 << " / " << n2 << ": " << n1 / n2 << '\n';
std::cout << n1 << " % " << n2 << ": " << n1 % n2 << '\n';

1
2
3
4
5
6
double n3 = 8.;
double n4 = 3.;
std::cout << n3 << " + " << n4 << ": " << n3 + n4 << '\n';
std::cout << n3 << " - " << n4 << ": " << n3 - n4 << '\n';
std::cout << n3 << " * " << n4 << ": " << n3 * n4 << '\n';
std::cout << n3 << " / " << n4 << ": " << n3 / n4 << '\n';

1
2
std::cout << "fmod(" << n3 << ", " << n4 << "): " << fmod(n3, n4) << '\n';
// This won't work: std::cout << n3 << " % " << n4 << ": " << n3 % n4 << '\n';

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
n1 += n2; // n1 = n1 + n2;
std::cout << "n1 after += is " << n1 << '\n';
n1 -= n2;
std::cout << "n1 after -= is " << n1 << '\n';
n1 *= n2;
std::cout << "n1 after *= is " << n1 << '\n';
n1 /= n2;
std::cout << "n1 after /= is " << n1 << '\n';
n1 %= n2;
std::cout << "n1 after %= is " << n1 << '\n';

1
2
3
4
n1++; // or n1 += 1; // or n1 = n1 + 1;
std::cout << "n1 after ++ is " << n1 << '\n';
n1--;
std::cout << "n1 after -- is " << n1 << '\n';

1
2
3
// same as n1 += 1; // or n1 = n1 + 1;
++n1;
std::cout << "n1 after ++ is " << n1 << '\n';

1
2
3
// same as n1 -= 1; // or n1 = n1 - 1;
--n1;
std::cout << "n1 after -- is " << n1 << '\n';

1
std::cout << "n1: " << n1++ << '\n';

1
std::cout << "n1: " << ++n1 << '\n';

Share Snippets