Increment/Decrement
Part of the Fundamentals section of Coddy's C journey — lesson 18 of 63.
In C, increment (++) and decrement (--) operators allow you to increase or decrease the value of a variable by 1.
Let's use an integer variable:
int counter = 5;To increment by 1, use the ++ operator:
counter++; // Increases counter to 6To decrement by 1, use the -- operator:
counter--; // Decreases counter to 5These operators can be used in two ways:
- Prefix form (++counter or --counter):
int a = 5;
int b = ++a; // a is incremented to 6, then b is assigned 6- Postfix form (counter++ or counter--):
int x = 5;
int y = x++; // y is assigned 5, then x is incremented to 6The difference is when the increment happens relative to the assignment.
Challenge
EasyCreate a program that:
- Declares an integer variable called
numberwith an initial value of 10 - Uses the prefix increment operator to increase
numberby 1 and assigns the result to a variable calledprefixResult - Uses the postfix increment operator on
numberand assigns the result to a variable calledpostfixResult - Prints the final value of
number,prefixResult, andpostfixResultin this exact format:
Number: [value]
Prefix result: [value]
Postfix result: [value]Cheat sheet
Increment (++) and decrement (--) operators increase or decrease a variable's value by 1:
int counter = 5;
counter++; // Increases counter to 6
counter--; // Decreases counter to 5Two forms available:
Prefix form: Increment/decrement happens first, then value is used
int a = 5;
int b = ++a; // a is incremented to 6, then b is assigned 6Postfix form: Value is used first, then increment/decrement happens
int x = 5;
int y = x++; // y is assigned 5, then x is incremented to 6Try it yourself
#include <stdio.h>
int main() {
// Write your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge