+ 1
Why i++ equal 5 and ++i equal 7 if i=5 in C# ?
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.
+ 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
+ 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.
+ 2
Cal Baksh
int i=5;
int j=i++;
int k=++i;
Console.WriteLine(j);
Console.WriteLine(k);