What is the difference between the add/decrement operator before or after a variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the difference between the add/decrement operator before or after a variable?

An example would be: i++ vs ++i or --i vs i--

11th Jan 2017, 7:17 PM
J.A.
6 Answers
+ 13
Post increment and pre increment. var i = 2; document.write(i++); The output of this code is 2. Why? This way of incrementing uses the value of i and then increments it. The opposite of this would be this: var i = 2; document.write(++i); The output of this code would be 3, because this way will increment the value and then use it. Hope this helps!
11th Jan 2017, 7:26 PM
Caleb Jore
Caleb Jore - avatar
+ 4
A simple example: public class NewMain { public static void main(String[] args) { int i = 0; while (i < 3) { System.out.println(++i + ". line"); } System.out.println(); i = 0; while (i < 3) { System.out.println(i++ + ". line"); } } } ----------- Output: 1. line 2. line 3. line 0. line 1. line 2. line
11th Jan 2017, 7:45 PM
Grzegorz Kawalec
Grzegorz Kawalec - avatar
+ 3
they are called prefix and postfix variables.... a++ = prefix ++a = postfix both will give you the same results because in both cases the a is being incremented but it is important when we use a second veriable.. --------------------------- like a=10; c = a++; and after that if i do printf("%d %d",c,a); then the.. c will have 10 and a will be 11 because 1st it assigns the variable into c then it increments the a ------------------------ like a=10; c = ++a; and after that if i do printf("%d %d",c,a); then the.. c will have 11 and a will be 11
12th Jan 2017, 9:13 PM
ARNAB BISWAS
ARNAB BISWAS - avatar
+ 2
pre increment adds 1 before operation post increment adds 1 after operation pre decrement subtracts 1 before operation post decrement subtracts 1 after operation
13th Jan 2017, 5:23 AM
Krushang Shah
Krushang Shah - avatar
+ 1
operator before a variable means change-then-use value i.e. it changes the value of the variable first then uses it whereas in operator after a variable use-then-change is being implemented..For eg. suppose i=5; then for {++i cout<<i; } Here output would be 6 whereas for {i++; cout<<i; } Here output would be 5 Similarly, {--i; cout<<i; } would show output 4 and; {i--; cout<<i; } would show output 5 which is assigned value.
12th Jan 2017, 12:28 PM
Sagar Bambhania
Sagar Bambhania - avatar
0
There are two types of operators in both add/decrement prefix(++x) and postfix(x++). In prefix increase the value before using. In postfix first use the value then increase. In decrement the decrease value
13th Jan 2017, 7:06 AM
Ritik
Ritik - avatar