Increment And Decrement Operators

This is used to increment the value of a variable by 1. This is denoted by the symbol “++”.   This can be used in two ways.

Case1 : Appending “++” operator after the variable name

Consider the operation “test++”.Here the value of the variable “test” will be incremented by 1.

Example

int test = 5;

test++;

Here the variable “test” will be initialized with a value 5. Then we use the increment operator to increment its value by 1. As a result, the value of the variable “test” will be incremented to 6.

Case2 : Prepending “++” operator before the variable name

Consider the operation “++test”.   Here the value of the variable “test” will be incremented by 1.

Example

int test = 5;

++test;

Here the variable “test” will be initialized with a value 5. Then we use the increment operator to increment its value by 1. As a result, the value of the variable “test”will be incremented to 6. 

Difference between these two Cases

In the first usage “variable_name++”, the current statement will be executed at first.   Then the value of the variable will be incremented by 1. Then the next statementwill be executed.

 In the second usage “++variable_name”, the value of the variable will be incremented   by 1 at first. Then the current statement will be executed. Then the next statement will be executed. 

Let’s make it clear with the following examples.

Example1

int value1 = 10;

int value2 = value1++; 

Here we are using the increment operator, appended to the variable name (case1).Can you predict the value of the variables “value2” and “value1”?

From the first line, variable “value1” gets a value 10.   Now comes the important part

“ int value2 = value1++; ”

Since we are using increment operator appended to the variable name (case1), the following actions follow

1. The value of the variable “value1” will be assigned to the variable “value2”. It means the variable “value2” gets 10 as its value.

2. Now the value of the variable “value1” will be incremented by 1. It means the value of the variable “value1” will be 11 now.

So at the end of this program, value1 will be 11 and value2 will be 10.

 

Advertisements

2 thoughts on “Increment And Decrement Operators

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s