In: Computer Science
Which codes add 1 to integer n?
1) n=n+1;
2) n++;
3)++n;
4) n+=1;
5) n=--n+2
Which codes add 1 to integer n:
Answer: All of the above
(1) n=n+1; (2) n++; (3) ++n; (4) n+=1; (5) n=--n+2;
Description:
(1) n = n + 1;
• The above statement Simply adds 1 to integer n as "n + 1".
• Example: Let's take integer n = 6 and apply n = n + 1 in the code, this will give the result n = 7.
Code:
Output:
(2) n++;
• The above statement is postfix or post-increment operator that adds 1 to integer n as "n++". This operator follows a rule 'use-then-change' means that n will be incremented first and then assigned to variable.
• Example: Let's take integer n = 6 and apply n++ in the code, this will give the result n = 7.
Code:
Output:
(3) ++n;
• The above statement is prefix or pre-increment operator that adds 1 to integer n as "++n". This operator follows a rule 'change-then-use' means that n will be assigned first to variable and then gets incremented.
• Example: Let's take integer n = 6 and apply ++n in the code, this will give the result n = 7.
Code:
Output:
(4) n+=1;
• The above statement is arithmetic assignment operator that adds 1 to integer n as "n+=1", which is simply n = n + 1.
• Example: Let's take integer n = 6 and apply n+=1 in the code, this will give result n = 7.
Code:
Output:
(5) n = --n+2;
• The above statement uses pre-decrement operator (--n) that will first decrement the n value by 1 and then adds 2 to it as "n = --n+2".
• Example: Let's take integer n = 6 and apply n= --n+2 in the code, this will give the result n = 7.
Code:
Output: