# Pre Increment Operators

## C - Difference between ++i and i++:

C offers several shorthand versions of the preceding type of assignment. When the operators precede (i.e., come before) the variable, the operation is called pre-increment and when the operators succeed (i.e., come after) the variable, the operations is called post-increment. Consider the following code snippets:

```
total = i++; /* Statement 1 */
and
total = ++i; /* Statement 2 */
```

The first statement is equivalent to:

```
total = i;
i = i + 1;
```

while the second statement is equivalent to:

```
i = i + 1;
total = i;
```

So, the said statements (1) and (2) do not have the same effect. The ++ in i++ is called post increment operator and ++i is called the pre increment operator.

**Example: ++i and i++**

```
#include <stdio.h>
int main()
{
int total = 100;
int i = 10;
printf("The initial value of total and i is : %d, %d", total, i);
total = ++i;
printf("\nAfter applying ++i value of total and i is : %d, %d", total, i);
total = 100;
i = 10;
printf("\n\nThe initial value of total and i is : %d, %d", total, i);
total = i++;
printf("\nAfter applying i++ value of total and i is : %d, %d", total, i);
return 0;
}
```

Output:

The initial value of total and i is : 100, 10 After applying ++i value of total and i is : 11, 11 The initial value of total and i is : 100, 10 After applying i++ value of total and i is : 10, 11

**++ in for construct:**

In the following for construct:

```
for (i =0; i++<5;..)
```

The value of i is compared 5 and then incremented, after which the loop is entered.

On the other hand, if the construct is modified to:

```
for (i=0; ++ i < 5;..)
```

The value of i is first incremented and then compared to 5 and then the loop is entered.

So in the first case the body of the loop will be executed 5 times and in the second case it will be executed 4 times only.

**Example: i++ in for construct:**

```
#include <stdio.h>
int main()
{
printf("i++ in for construct:");
for (int i =0; i++<5;)
{
printf("\nValue of i is %d",i);
}
return 0;
}
```

Output:

i++ in for construct: Value of i is 1 Value of i is 2 Value of i is 3 Value of i is 4 Value of i is 5

**Example: ++i in for construct:**

```
#include <stdio.h>
int main()
{
printf("++i in for construct:");
for (int i =0; ++i<5;)
{
printf("\nValue of i is %d",i);
}
return 0;
}
```

Output:

++i in for construct: Value of i is 1 Value of i is 2 Value of i is 3 Value of i is 4

**Weekly Trends**- 100 Python Projects for Beginners with solution
- Mastering NumPy: 100 Exercises with solutions
- SQL Tutorial
- SQL Inner Join
- Python Exercises, Practice, Solution
- Python Interview Questions and Answers: Comprehensive Guide
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript HTML Form Validation
- Java Collection Exercises