I’m Learning C# – Part 3

Arithmetic operations – +, , *, /, %

Following is a code which will read in 2 numbers from the console and perform subtraction operation between them. Similar concept can be expanded to other operators.

int x;
int y;
Console.WriteLine(“Enter the numbers”);
x = Convert.ToInt16(Console.ReadLine());
y = Convert.ToInt16(Console.ReadLine());
Console.WriteLine(“difference = {0}”, x-y);

Main thing to remember is that ReadLine takes in only string. So it is required to convert it into the required data type by using the Convert.To<>.

If there are multiple operators in an equation, follow BODMAS.

x +=5; //This is same as x=x+5   This is a form of shorthand.

x++; //Same as x=x+1

++x and x++ are 2 different things. The first one increases the value of x then and there, the other one only in the next iteration.

int x=4; y= x++; //y =4, x= 5

int x=4; y=++x; //y = 5, x=5


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s