C# Decrement Int

Int keyword

Decrement reduces the value of a number. The decrement operator receives one or two operands. It is written with the characters -­- or -=. We use this operator in a loop iteration statement—or in any context where statements are permitted.

These C# example programs show how decrement works. Syntax and expressions are covered.

Example 1

Note

To start, we see a simple program written in the C# language that introduces a local variable integer called i. The character i is a classic name for a loop iteration variable; these variables are also called induction variables. Here, we start the value stored in the variable location with the integer 100. Then, the single decrement operator -­- is applied; this decreases the value by 1. Then, we use the -= operator and use several different operands with it.

Program that uses decrement operators [C#]

using System;

class Program
{
    static void Main()
    {
	int i = 100;
	// Decrement by 1.
	i--;
	Console.WriteLine(i);
	// Decrement by 2.
	i -= 2;
	Console.WriteLine(i);
	// Decrement by negative 1 (add 1).
	i -= -1;
	Console.WriteLine(i);
	// Decrement by 0 (do nothing).
	i -= 0;
	Console.WriteLine(i);
	// Decrement by itself (results in 0).
	i -= i;
	Console.WriteLine(i);
    }
}

Output

99
97
98
98
0

Bit representation. We have already introduced the concepts of variables and values in this program. The values (such as 100) are actually stored in a bit representation format in the hardware. When you apply a mathematical transformation to the integer, the resulting bit representation is changed in a well-known way as well.

Pre and post decrement

There are two forms of the decrement by one operator. These are called the post-decrement and pre-decrement operators. These forms are both considered unary operators, meaning they can only receive one operand. When you use the post-decrement operator in an expression, the expression is evaluated before the decrement occurs; when you use the pre-decrement operator, it is evaluated after.

Program that uses two forms of decrement [C#]

using System;

class Program
{
    static void Main()
    {
	int i = 5;
	// This evaluates to true because the decrement occurs after the comparison.
	if (i-- == 5)
	{
	    Console.WriteLine(true);
	}
	// This evaluates to true because the decrement occurs before the comparison.
	if (--i == 3)
	{
	    Console.WriteLine(true);
	}
    }
}

Output

True
True

Summary

The C# programming language

There are many different ways of decrementing variables using the decrement operators in the C# programming language. Please remember that you can also use expressions to decrement values, even without these operators. It can be difficult to deal with programs that rely on the nuances of the order of evaluation of these operators; because of this, it is best to avoid these situations entirely.

Number Examples
.NET