Advertisements
Advertisements
Question
Evaluate the following expression where prefix and postfix increment and decrement operator is used.
int p=3, q=20, r=0;
r = ++p + p++ + q++ + q++;
System.out.println ("P=" + p+ “Q="+ q+ “R="+ r);
Evaluate
Advertisements
Solution
++p (Prefix): Increments p first (from 3 to 4), then uses this new value (4) in the expression. Now, p = 4.
p++ (Postfix): Uses the current value of p (4) in the expression, then increments p to 5. Now, p = 5.
q++ (Postfix): Uses the current value of q (20) in the expression, then increments q to 21. Now, q = 21.
q++ (Postfix): Uses the current updated value of q (21) in the expression, then increments q to 22. Now, q = 22
- R = 4 + 4 + 20 + 21 = 49
- P = 5
- Q = 22
shaalaa.com
Is there an error in this question or solution?
Chapter 1: Revision of Class 9 Syllabus - Exercises [Page 45]
