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
VulpesPosted Nov 22, 2011, 3:31 PM
So, if you have this line:
Posted Nov 22, 2011, 3:12 PM
VulpesPosted Nov 22, 2011, 9:26 AM
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, 9:05 AM
VulpesPosted Nov 22, 2011, 8:50 AM
Posted Nov 22, 2011, 7:17 AM
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
NarayanPosted Nov 22, 2011, 2:12 AM
If you would have written something
w=n++;
or
x=++n;
result will be different.
Posted Nov 22, 2011, 12:18 AM
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.
NarayanPosted Nov 21, 2011, 9:16 PM
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