When to use i++ or ++i in C++?

C++ProgrammingServer Side Programming

Increment operators are used to increase the value by one while decrement works opposite. Decrement operator decrease the value by one.

Pre-increment (++i) − Before assigning the value to a variable, the value is incremented by one.

Post-increment (i++) − After assigning the value to a variable, the value is incremented.

Here is the syntax of i++ and ++i in C++ language,

++variable_name; // Pre-increment
variable_name++; // Post-increment

Here,

variable_name −Name of the variable given by user.

Here is an example of pre and post increment in C++ language,

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int i = 5;
   cout << "The pre-incremented value: " << i;
   while(++i < 10 )
   cout<<"\t"<<i;
   cout << "\nThe post-incremented value: " << i;
   while(i++ < 15 )
   cout<<"\t"<<i;
   return 0;
}

Output

The pre-incremented value: 56789
The post-incremented value: 101112131415

In the above program, the code of pre and post increment exists in main() function. The variable i of integer type is pre-incremented until value of i is less than 10 and post-incremented until the value of i is less than 15.

while(++i < 10 )
printf("%d\t",i);
cout << "\nThe post-incremented vaue : " << i;
while(i++ < 15 )
printf("%d\t",i);
raja
Published on 05-Nov-2018 11:25:35
Advertisements