Increment/Decrement
Part of the Fundamentals section of Coddy's C++ journey — lesson 18 of 74.
Increment and decrement operators are used to increase or decrease the value of a variable by 1. These operators are widely used in programming, especially in loops and counters.
The increment operator is represented by two plus signs ++, and the decrement operator is represented by two minus signs --.
For example, to increment a variable named count, you can use the increment operator like this:
int count = 5;
count++; // count is now 6Similarly, to decrement a variable named value, you can use the decrement operator like this:
int value = 10;
value--; // value is now 9The ++ and -- operators are special shortcuts that ONLY work for adding or subtracting 1. There is no ** or similar operator for multiplication.
For regular arithmetic operations (like multiplication, division, or adding/subtracting by amounts other than 1), you must use the assignment pattern:
int count = 5;
count = count + 3; // Add 3: count is now 8
count = count * 2; // Multiply by 2: count is now 16
count = count - 4; // Subtract 4: count is now 12Challenge
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:
- Use the increment operator (
++) four times to add 4 to count - Use the multiplication operator (
*) to multiply count by 2 - Use the decrement operator (
--) once to subtract 1 from count
Cheat sheet
Increment and decrement operators are used to increase or decrease the value of a variable by 1.
The increment operator ++ increases a variable by 1:
int count = 5;
count++; // count is now 6The decrement operator -- decreases a variable by 1:
int value = 10;
value--; // value is now 9The ++ and -- operators are special shortcuts that ONLY work for adding or subtracting 1. There is no ** or similar operator for multiplication.
For regular arithmetic operations (like multiplication, division, or adding/subtracting by amounts other than 1), you must use the assignment pattern:
int count = 5;
count = count + 3; // Add 3: count is now 8
count = count * 2; // Multiply by 2: count is now 16
count = count - 4; // Subtract 4: count is now 12Try 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