Start learning free

LESSON 26 OF 674 · CALCULATIONS WITH NUMBERS

Increment & Decrement Operators in C#

Lesson

In programming, increasing the value of a variable by 1 is so common, there is an operator designed to do that.

That operator is the increment operator (++):

int number = 10;
number++; // short for number += 1

Console.WriteLine(number); // Output: 11

There is also one such operator for decreasing the value of a variable by 1.

That operator is the decrement operator (--):

int number = 10;
number--; // short for number -= 1

Console.WriteLine(number); // Output: 9

Postfix:

In the examples above, we have used these two operators in their postfix form, with operator (++) after operand (number) such as number++.

If used postfix, the increment operator increments and returns the value before incrementing:

int number = 10;

int oldNumber = number++;

Console.WriteLine(oldNumber); // Output: 10
Console.WriteLine(number); // Output: 11

This code first assigns the value of number (which is 10) to oldNumber and then increments number (making it 11). It's equivalent to this:

int oldNumber = number;
number++;

Prefix:

However, there is also the prefix form, with operator before operand (for example, ++number).

When used prefix, the increment operator increments and returns the value after incrementing:

int number = 10;

int newNumber = ++number;

Console.WriteLine(newNumber); // Output: 11
Console.WriteLine(number); // Output: 11

This code first increments number (making it 11) and then assigns the new value of number to newNumber (making it 11). It's equivalent to this:

number++;
int newNumber = number;

Here's an example with the decrement operator:

int number = 10;

int newNumber = --number;

Console.WriteLine(newNumber); // Output: 9
Console.WriteLine(number); // Output: 9

Assignment
Follow the Coding Tutorial and let's practice with these operators!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check