ASP.NET Basics (part 2): Not My Type - Operate With Caution
(Page 6 of 10 )
You'll remember how, in the first part of this tutorial, I used the + operator to add strings together. And just as you have the + operator for concatenating strings, C# comes with a bunch of other arithmetic operators designed to simplify the task of performing mathematical operations.
The following example demonstrates the important arithmetic operators available in C#:
<script language="C#" runat="server">
void Page_Load()
{
// define some numeric variables
int alpha, beta;
// and some more
int sum, difference, product, quotient;
// initialize them
alpha = 69;
beta = 96;
sum = alpha + beta; // addition
difference = beta - alpha; // subtraction
product = alpha * beta; // multiplication
quotient = beta / alpha; // integer division
addition.Text = "Sum of " + alpha + " and " + beta + " is " + sum + ".";
subtraction.Text = "Difference of " + beta + " and " + alpha + " is " + difference + ".";
multiplication.Text = "Product of " + alpha + " and " + beta + " is " + product + ".";
division.Text = "Quotient of " + beta + " by " + alpha + " is " + quotient
+ ".";
}
</script>
<html>
<head><title>Math Class</title></head>
<body>
<asp:label id="addition" runat="server" />
<asp:label id="subtraction" runat="server" />
<asp:label id="multiplication" runat="server" />
<asp:label id="division" runat="server" />
</body> </html>
And here is the output:

As with all other programming languages, division and multiplication take precedence over addition and subtraction, although parentheses can be used to give a particular operation greater precedence. For example, the following statement
<%
result = 10 + 2 * 4;
%>
will store 18 in "result", while
<%
result = ((10 + 2) * 4);
%>
assigns 48 to the variable.
In addition to these operators, C# comes with the very useful auto-increment (++) and auto-decrement (--) operators, which you'll see a lot of in forthcoming articles. The auto-increment operator increments the value of the variable by 1. The auto-decrement operator does the opposite. Here's an example which illustrates how this works
<script language="C#" runat="server">
void Page_Load()
{
// define a variable
int x=99;
x++;
// now x = 100
x--;
// now x = 99
}
</script>
Next: Everything Must Go >>
More ASP.NET Code Articles
More By Harish Kamath (c) Melonfire