In the following program I entered 10, results are 10, 11, 12 and 11 respectively. Please explain the reason.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace prefix_postfix1
{
class Program
{
static void Main(string[] args)
{
string entry;
int w, x, y, z, n;
Console.Write("Enter an integer ");
entry = Console.ReadLine();
n = Convert.ToInt32(entry);
w = n;
n++;
Console.WriteLine("{0}", w);//output=10
x = n;
++n;
Console.WriteLine("{0}", x);//output=11
y = n;
n--;
Console.WriteLine("{0}", y //output=12
z = n;
--n;
Console.WriteLine("{0}", z);//output=11
Console.ReadKey();
}
}
}
Loading

NarayanRank #8,477 · 221 reputationPosted Nov 21, 2011, 4:16 PM EST
you have assigned it to w, so value of w=10.
Then n++; will change the value of n to 11 and you have assigned it to x
So value of x will be 11.
Then ++n again value of n is changed to 12 and you have assigned it to y so value will be 12
then n-- will change the value of n to 11 and has been assigned to z , so value of z will be 11
Posted Nov 21, 2011, 7:18 PM EST
That mean 2nd statement is just copying the calculated value of 1st statement.
3rd statement is just copying the calculated value of 2nd statement.
4th statement is just copying the calculated value of 3rd statement.
NarayanRank #8,477 · 221 reputationPosted Nov 21, 2011, 9:12 PM EST
If you would have written something
w=n++;
or
x=++n;
result will be different.
Posted Nov 22, 2011, 2:17 AM EST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string entry;
int n;
Console.Write("Enter an integer ");
entry = Console.ReadLine();
n = Convert.ToInt32(entry);
Console.WriteLine("A = {0}", n++);//A=10
Console.WriteLine("B = {0}", ++n);//B=12
Console.WriteLine("C = {0}", n--);//C=12
Console.WriteLine("D = {0}", --n);//D=10
Console.ReadKey();
}
}
}
The output must be according to my understanding A=10, B=11, C=11 and D=10
VulpesRank #55 · 29.2K reputationPosted Nov 22, 2011, 3:50 AM EST
Posted Nov 22, 2011, 4:05 AM EST
VulpesRank #55 · 29.2K reputationPosted Nov 22, 2011, 4:26 AM EST
Prefix notation (++n, --n) increments or decrements 'n' before carrying out the current operation on 'n'.
Postfix notation (n++, n--) increments or decrements 'n' after carrying out the current operation on 'n'.
Posted Nov 22, 2011, 10:12 AM EST
VulpesRank #55 · 29.2K reputationPosted Nov 22, 2011, 10:31 AM EST
So, if you have this line: