Menu
Coddy logo textTech

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 6

To decrement by 1, use the -- operator:

counter--;  // Decreases counter to 5

These operators can be used in two ways:

  1. Prefix form (++counter or --counter):
int a = 5;
int b = ++a;  // a is incremented to 6, then b is assigned 6
  1. Postfix form (counter++ or counter--):
int x = 5;
int y = x++;  // y is assigned 5, then x is incremented to 6

The difference is when the increment happens relative to the assignment.

challenge icon

Challenge

Easy

Create a program that:

  1. Declares an integer variable called number with an initial value of 10
  2. Uses the prefix increment operator to increase number by 1 and assigns the result to a variable called prefixResult
  3. Uses the postfix increment operator on number and assigns the result to a variable called postfixResult
  4. Prints the final value of number, prefixResult, and postfixResult in 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 5

Two 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 6

Postfix form: Value is used first, then increment/decrement happens

int x = 5;
int y = x++;  // y is assigned 5, then x is incremented to 6

Try it yourself

#include <stdio.h>

int main() {
    // Write your code here
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals