Arithmetic Shortcuts
Part of the Fundamentals section of Coddy's C++ journey — lesson 20 of 74.
C++ created a cool shortcut for self-arithmetic operations.
For example instead of writing:
int a = 5;
a = a + 3; // a holds 8We can simplify it by writing +=:
int a = 5;
a += 3; // a holds 8The += is adding to a itself the value 3
This operation is valid for all arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Challenge
BeginnerYou are given a code with initialization of count. (Don't delete this line!)
Your task is to add the following operations, in this order:
- Add
4tocount - Multiply
countby2 - Subtract
1fromcount
Use the arithmetic shortcuts to do so!
Cheat sheet
C++ provides shortcut operators for self-arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Instead of writing:
int a = 5;
a = a + 3; // a holds 8You can use the shortcut:
int a = 5;
a += 3; // a holds 8Try it yourself
#include <iostream>
int main() {
int count = 0;
// Type your code below
// Don\'t change the line below
std::cout << "count = " << count;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else