Why i++ equal 5 and ++i equal 7 if i=5 in C# ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why i++ equal 5 and ++i equal 7 if i=5 in C# ?

12th Jun 2018, 2:04 PM
Phichitphol Bunyakanok
Phichitphol Bunyakanok - avatar
4 Answers
+ 6
If you are doing something like this. int i = 5; Console.WriteLine(i++) // outputs 5 Console.WriteLine(++i) //outputs 7 This is because It print the value of i and then increment it. This print 5 and increment it to 6. But in the next statement, It is pre-incremented. Therefore, it increments the value first and then prints it. Therefore, the output is 7.
12th Jun 2018, 2:11 PM
Akash Pal
Akash Pal - avatar
+ 3
Using Console.WriteLine() gives the impression that you are just showing and not changing whats inside pre-increment and post increment operators Will alter the value. int i = 5; Console.WriteLine(i++); // outputs 5 Console.WriteLine(i); // outputs 6 Console.WriteLine(++i); //outputs 7 int i = 5; Console.WriteLine(++i); // outputs 6 Console.WriteLine(i++); //outputs 6 Console.WriteLine(i); //outputs 7
23rd Jun 2018, 7:14 PM
sharpProgrammer - avatar
+ 2
Could you provide the code you used to test this? i++ should equal 5 and ++i should equal 6 if i is equal to 5. This is because the prefix operator (++i) increments the variable, then returns it, whereas the postfix operator (i++) returns the value then returns it.
12th Jun 2018, 2:16 PM
Cailyn Baksh
+ 2
Cal Baksh int i=5; int j=i++; int k=++i; Console.WriteLine(j); Console.WriteLine(k);
12th Jun 2018, 2:19 PM
Phichitphol Bunyakanok
Phichitphol Bunyakanok - avatar