Sunday, July 14, 2013

Program on Increment Operator

Most of the people are confused every time in analyzing the Increment Operators because they actually do. We should be careful in analyzing the Pre-Increment and Post-Increment Operators.

In most of the competitive exams, we come across a problem on Increment Operators. We should be careful enough in solving the problems on Increment Operators.

Consider the following example, to understand the Increment and Decrement Operators.

Let us take

a=1;
b=a + a++ + ++a;

People are confused in solving such a problem. In solving that equation, we have to go through the Operator precedence. As per the Operator precedence, Increment Operator has more precedence than any other operator. So first the Increment Operators are given more priority.

In the above equation, we have one pre-increment and one post-increment operator. As we know, post-increment takes effect after taking the value. So, we have to take care of only pre-increment. Pre-increment changes the value of a to be 2. Hence in place of all others, we take 2 and hence the result is 6 and a is 3 after that equation.

If we change the b to be as a + a++ + ++a + a++;
In the above expression, we have just added  a++ to the previous one. As this is post increment, it takes the effect after execution. Hence b is 8 and a becomes 4 after execution.

I think now you are clear about the Increment Operators.

Check out the following example for more clear understanding,

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=1,b;
  5. b= a+ ++a + a++;
  6. printf("%d %d,b,a);
  7. return 0;
  8. }
Add as many pre-increment and post-increment operators to the above program. You will understand with more practice.

But still you have a unsolved question. What happens, if we use the complete expression in printf() instead of assigning to a variable? Click here to know more.