Operators
Most things a program does involve some math: a total price, an average score, how many are left. In C++ the four basic operations look much like they do in math, with * for times and / for divide:
1#include <iostream>2 3int main() {4 int apples = 12;5 int pears = 5;6 std::cout << apples + pears << '\n';7 std::cout << apples - pears << '\n';8 std::cout << apples * pears << '\n';9 std::cout << apples / pears << '\n';10 return 0;11}
17 7 60 2
No surprises in the first three lines. In the last one, 12 divided by 5 isn't 2.4. It's 2.
Integer division and remainders
Dividing one int by another gives an int: the decimal part is simply dropped, not rounded. To get what was dropped, use %, the remainder:
1#include <iostream>2 3int main() {4 int minutes = 135;5 std::cout << minutes / 60 << " hours\n";6 std::cout << minutes % 60 << " minutes\n";7 return 0;8}
2 hours 15 minutes
135 minutes hold 2 whole 60s, with 15 left over. % comes up a lot: if n % 2 is 0, n is even; n % 10 is the last digit. % works only on whole numbers.
8 slices of pizza for 3 people: what does this show?
1#include <iostream>2 3int main() {4 int slices = 8;5 int people = 3;6 std::cout << slices / people << " " << slices % people << '\n';7 return 0;8}
8 / 3 is integer division: 2 slices each, decimals dropped. 8 % 3 is the 2 slices left over.
static_cast: getting decimals
When you work out an average, integer division is a trap:
1#include <iostream>2 3int main() {4 int total = 7;5 int count = 2;6 double wrong = total / count;7 double right = static_cast<double>(total) / count;8 std::cout << wrong << '\n';9 std::cout << right << '\n';10 return 0;11}
3 3.5
wrong is a double, but total / count had already been worked out as the whole number 3 before it went in. static_cast<double>(total) turns total into the double 7.0 first, so the division keeps its decimals: 3.5. If either side is a double, division keeps decimals, so 7.0 / 2 works too.
Tip: In C code you'll see (double)total, which does the same. In C++ use static_cast: it stands out more and is easier to search for.
+= and ++
"Add this much to what's there" is so common that it has a short form: stock += 5 means stock = stock + 5. -=, *=, /= and %= work the same way. Adding or taking away 1 is shorter still: ++count and --count.
1#include <iostream>2 3int main() {4 int stock = 10;5 stock += 5;6 stock -= 3;7 stock *= 2;8 int sold = 0;9 ++sold;10 ++sold;11 std::cout << "Stock: " << stock << ", sold: " << sold << '\n';12 return 0;13}
Stock: 24, sold: 2
Press Step to watch stock go from 10 to 15, 12, then 24. You can put ++ before (++sold) or after (sold++); on a line of its own it does the same either way. This course keeps it on a line of its own, not inside a longer expression.
Multiplication before addition
As in math, *, / and % go before + and -; operators at the same level go from left to right. When in doubt, add parentheses:
1#include <iostream>2 3int main() {4 int a = 80;5 int b = 90;6 std::cout << a + b / 2 << '\n';7 std::cout << (a + b) / 2 << '\n';8 std::cout << 10 - 4 - 3 << '\n';9 return 0;10}
125 85 3
The first line works out b / 2 first, 45, then adds 80: 125, which is not the average. With parentheses it's 85. 10 - 4 - 3 goes from left to right, giving 3.
What does this program show?
1#include <iostream>2 3int main() {4 std::cout << 2 + 3 * 4 << '\n';5 return 0;6}
The multiplication 3 * 4 comes first, giving 12, then 2 is added: 14. To add first, write (2 + 3) * 4.
The limits of int
An int usually takes 4 bytes, so the numbers it can hold have a top and a bottom. INT_MAX and INT_MIN from <climits> are those two numbers. std::numeric_limits<int>::max() and min() from <limits> are another way to write them, and they work for other types too:
1#include <iostream>2#include <climits>3#include <limits>4 5int main() {6 std::cout << INT_MAX << '\n';7 std::cout << INT_MIN << '\n';8 std::cout << std::numeric_limits<int>::max() << '\n';9 std::cout << std::numeric_limits<long long>::max() << '\n';10 return 0;11}
2147483647 -2147483648 2147483647 9223372036854775807
For int that's about 2.1 billion either way; the third line is the same number as the first. The last line is the largest long long, much bigger. Going past this range is called overflow. See what happens when you add 1 to the largest one:
1#include <iostream>2#include <climits>3 4int main() {5 int views = INT_MAX;6 std::cout << "Now: " << views << '\n';7 views = views + 1;8 std::cout << "Plus 1: " << views << '\n';9 return 0;10}
Now: 2147483647
signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'What happened: Stopped at line 7. The result doesn't fit in its type: the number is too big.
Overflowing an int is undefined behavior. On an ordinary computer it often turns quietly into a large negative number and the program carries on, so the mistake is hard to spot. Our engine stops at the line where it overflows. When a number may get very big (the world's population, an amount in cents), use long long instead, which goes up to about 9×10¹⁸.
sqrt and pow
Math functions such as square roots and powers are in <cmath>. std::sqrt(x) is the square root, and std::pow(x, y) is x to the power y; both give a double:
1#include <iostream>2#include <cmath>3 4int main() {5 std::cout << std::sqrt(16.0) << '\n';6 std::cout << std::pow(2, 10) << '\n';7 double a = 3;8 double b = 4;9 std::cout << "Long side: " << std::sqrt(a * a + b * b) << '\n';10 return 0;11}
4 1024 Long side: 5
C++ has no power operator: 2 ^ 10 compiles, but ^ is a different operation and gives 8, not 1024. For powers use std::pow; for a square, just write a * a.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Average of three scores
✓Right now the program shows Average: 89. Change it to show the average with decimals: Average: 89.6667.
Average: 89.6667
1#include <iostream>2 3int main() {4 int math = 85;5 int english = 90;6 int science = 94;7 int total = math + english + science;8 std::cout << "Average: " << total / 3 << '\n';9 return 0;10}
Minutes into hours
✓Use / and % to turn minutes into hours and minutes, and show 200 minutes is 3 h 20 min.
200 minutes is 3 h 20 min
1#include <iostream>2 3int main() {4 int minutes = 200;5 6 return 0;7}
Fix it: too many steps
✓Run it: the engine stops at the line that overflows. Fix it so it shows 4000000000.
4000000000
1#include <iostream>2 3int main() {4 int steps = 2000000000;5 int total = steps + steps;6 std::cout << total << '\n';7 return 0;8}
What you learned
+ - * /add, subtract, multiply and divide; oneintdivided by another is integer division, and the decimals are dropped.%is the remainder, for whole numbers only:n % 2tells odd from even,n % 10is the last digit.static_cast<double>(x)turnsxinto adouble, so division keeps its decimals.x += 5is short forx = x + 5;++xadds 1 and--xtakes 1 away.- Multiplication and division go before addition and subtraction, same level left to right; when in doubt, use parentheses.
- The largest
intisINT_MAX(std::numeric_limits<int>::max()), about 2.1 billion; overflow is undefined behavior, so uselong longfor big numbers. <cmath>hasstd::sqrtandstd::pow;^is not a power.