Home

Operators and Operands

 

Fundamental C# Operators

 

Introduction

An operation is an action performed on one or more values either to modify the value held by one or both of the variables, or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and at least one value. The symbol used in an operation is called an operator. A value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands.

Semi-Colon;

The semi-colon is used to indicate the end of an expression or a declaration. Here is an example:

using System;

As we will learn when studying the for conditional statement, there are other uses of the semi-colon.

 

Practical LearningPractical Learning: Introducing the Semi-Colon

  1. Start Notepad and, in the empty file, type the following:
     
    using System;
  2. Save the file in a new folder named GCS2
  3. Save the file itself as Exercise.cs

Curly Brackets { }

Curly brackets are probably the most used and the most tolerant operators of C#. Fundamentally, curly brackets are used to create a section of code. As such they are required to delimit the bodies of namespaces, classes, structures, exceptions, etc. They are also optionally used in conditional statements. Curly brackets are also used to create variable scope.

Here is an example:

using System;

class Exercise
{
}

Practical LearningPractical Learning: Using Curly Brackets

  1. To use curly brackets, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    }
  2. Save the file
 

Parentheses ( )

Like most computer languages, C# uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, parentheses are used to differentiate a method such as Main from a regular variable. Here is an example:

using System;

class Exercise
{
	static void Main()
	{
	}
}

Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression.

Practical LearningPractical Learning: Using Parentheses

  1. To use parentheses, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			double MondayDiscount;
    		}
    	}
    }
  2. Save the file

The Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared with the same data type. Here is an example:

using System;

class Exercise
{
	static void Main()
	{
		string FirstName, LastName, FullName;
	}
} 

The comma can also be used to separate the member of an enumerator or the arguments of a method. We will review all of them when the time comes.

Practical LearningPractical Learning: Using Commas

  1. To use commas, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			string CustomerName, HomePhone;
    			uint NumberOfShirts, NumberOfPants, NumberOfDresses;
    			decimal PriceOneShirt, PriceAPairOfPants, PriceOneDress;
    			uint OrderMonth, OrderDay, OrderYear;
    			double MondayDiscount;
    		}
    	}
    }
  2. Save the file

The Assignment =

When you declare a variable, a memory space is reserved for it. That memory space may be empty until you fill it with a value. To "put" a value in the memory space allocated to a variable, you can use the assignment operator represented as =. Based on this, the assignment operation gives a value to a variable. Its syntax is:

VariableName = Value

The VariableName factor must be a valid variable name. It cannot be a value such as a numeric value or a (double-quoted) string. Here is an example that assigns a numeric value to a variable:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			decimal Salary;

			// Using the assignment operator
			Salary = 12.55M;
		}
	}
}

Once a variable has been declared and assigned a value, you can call Write() or WriteLine() to display its value.  Here is an example:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			decimal Salary;

			// Using the assignment operator
			Salary = 12.55M;
			System.Console.Write("Employee's Hourly Salary: ");
			System.Console.WriteLine(Salary);
		}
	}
}

This would produce:

Employee's Hourly Salary: $12.55

The above code declares a variable before assigning it a value. You will usually perform this assignment when you want to change the value held by a variable. Providing a starting value to a variable when the variable is declared is referred to as initializing the variable. Here is an example:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// Using the assignment operator
			decimal Salary = 12.55M;

			System.Console.Write("Employee's Hourly Salary: ");
			System.Console.WriteLine(Salary);
		}
	}
}

We saw that you can declare various variables at once by using the same data type but separating their names with commas. When doing this, you can also initialize each variable by assigning it the desired value before the comma or the semi-colon. Here is an example:

 
namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// Initializing various variables when declaring them with the same data type
			double Value1 = 224.58, Value2 = 1548.26;
			
			System.Console.Write("Value 1 = ");
			System.Console.WriteLine(Value1);
			System.Console.Write("Value 2 = ");
			System.Console.WriteLine(Value2);
			System.Console.WriteLine();
		}
	}
}

This would produce:

Value 1 = 224.58
Value 2 = 1548.26
 

Practical LearningPractical Learning: Assigning Values to Variables

  1. To use the assignment operator, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			string CustomerName, HomePhone;
    			uint NumberOfShirts        = 5,
    				 NumberOfPants    = 2,
    				 NumberOfDresses  = 0;
    			decimal PriceOneShirt      = 0.95M,
    				    PriceAPairOfPants = 2.95M,
    				    PriceOneDress     = 4.55M;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    			double MondayDiscount = 0.25; // 25%;
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Save the file

Single-Quote '

The single quote is used to include one character to initialize, or assign a symbol to, a variable declared as char. A single is usually combined with another and a character is included between them. Here is an example:

using System;

class Exercise
{
	static void Main()
	{
		char Gender;
		string FirstName, LastName, FullName;

		Gender = 'M';
	}
}

You can include only one character between single-quotes except if the combination of symbols can be evaluated to one character. This is the case for escape sequences. Here is an example:

using System;

class Exercise
{
	static void Main()
	{
		Console.WriteLine('\n');
	}
}

Double-Quotes "

The double-quote " is used to delimit a string. Like the single-quote, the double-quote is usually combined with another. Between the combination of double-quotes, you can include an empty space, a character, a word, or a group of words, making it a string. Here is an example:

using System;

class Exercise
{
	static void Main()
	{
		Console.WriteLine("The Wonderful World of C#!!!");
	}
}

A double-quoted string can also be declared and then assigned to a variable.

Practical LearningPractical Learning: Using Quotes

  1. To use single and double-quotes, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			string CustomerName = "James Burreck",
    				   HomePhone = "(202) 301-7030";
    			uint NumberOfShirts   = 1,
    				 NumberOfPants    = 1,
    				 NumberOfDresses  = 1;
    			decimal PriceOneShirt     = 0.95M,
    				    PriceAPairOfPants = 2.95M,
    				    PriceOneDress     = 4.55M;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    			double MondayDiscount = 0.25; // 25%;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("========================");
    			Console.Write("Customer:   ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone: ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Order Date: ");
    			Console.Write(OrderMonth);
    			Console.Write('/');
    			Console.Write(OrderDay);
    			Console.Write('/');
    			Console.WriteLine(OrderYear);
    			Console.WriteLine("------------------------");
    			Console.WriteLine("Item Type  Qty Sub-Total");
    			Console.WriteLine("------------------------");
    			Console.Write("Shirts      ");
    			Console.Write(NumberOfShirts);
    			Console.Write("     ");
    			Console.WriteLine(PriceOneShirt);
    			Console.Write("Pants       ");
    			Console.Write(NumberOfPants);
    			Console.Write("     ");
    			Console.WriteLine(PriceAPairOfPants);
    			Console.Write("Dresses     ");
    			Console.Write(NumberOfDresses);
    			Console.Write("     ");
    			Console.WriteLine(PriceOneDress);
    			Console.WriteLine("------------------------");
    			Console.Write("Monday Discount: ");
    			Console.Write(MondayDiscount);
    			Console.WriteLine('%');
    			Console.WriteLine("========================");
    			Console.WriteLine();
    		}
    	}
    }
  2. Save the file
  3. At the Command Prompt, change to the GCS2 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      1     0.95
    Pants       1     2.95
    Dresses     1     4.55
    ------------------------
    Monday Discount: 0.25%
    ========================
  6. Return to Notepad

Square Brackets [ ]

Square brackets are mostly used to control the dimension or index of an array. We will learn how to use them when we study arrays. Here is an example from a future lesson:

using System;

namespace CSharpLessons
{
    class Exercise
    {
	static void Main()
	{
	    double[] number = new double[5];

             number[0] = 12.44;
             number[1] = 525.38;
	    number[2] = 6.28;
             number[3] = 2448.32;
             number[4] = 632.04;

             Console.WriteLine();
	}
    }
}

The Positive Operator +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞
   0
-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value doesn't display a sign, it is referred as unsigned.

To express a variable as positive or unsigned, you can just type it. here is an example:

using System;

class Exercise
{
	static void Main()
	{
		// Displaying an unsigned number
		Console.Write("Number = ");
		Console.WriteLine(+802);
	}
}

This would produce:

Number = 802

The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Here is an example that uses two variables. One has a positive value while the other has a negative value:

using System;

class Exercise
{
	static void Main()
	{
		// Displaying an unsigned number
		Console.Write("First Number  ");
		Console.WriteLine(+802);
		// Displaying a negative number
		Console.Write("Second Number ");
		Console.WriteLine(-802);
	}
}

This would produce:

First Number  802
Second Number -802
 

Unary Operators: The sizeof Operator

We have already seen that when declaring a variable, the compiler reserves a portion of space in the computer memory to hold that variable. We also illustrated how much space some data types need to store their variable. C++ provides the unary sizeof operator that allows you to find out how much space a data type. You can use the sizeof operator as unsafe in your C# application.

To find out how much memory space a data type uses, type it between the parentheses of the sizeof operator. Remember that sizeof is unsafe. Therefore, a method that uses it must be preceded with the unsafe keyword. Here is an example:

using System;

class Exercise
{
	unsafe static void Main()
	{
		double Period = 155.50;
		int SizeOf = sizeof(double);

		Console.Write("The value ");
		Console.Write(Period);
		Console.Write(" uses ");
		Console.Write(SizeOf);
		Console.WriteLine(" bytes\n");
	}
}

This would produce:

The value 155.5 uses 8 bytes

Practical LearningPractical Learning: Using the sizeof Operator

  1. Start a new file in Notepad and type the following:
     
    using System;
    
    class Exercise
    {
    	unsafe static void Main()
    	{
    		// The sizeof operator used to get the memory size used by 
    		// a variable declared with a certain a data type
    		Console.WriteLine("The sizeof Operator");
    		Console.WriteLine("==========================");
    		Console.WriteLine("Data Type     Memory Size");
    		Console.WriteLine("--------------------------");
    		Console.Write("char           ");
    		Console.Write(sizeof(char));
    		Console.WriteLine("  Bytes");
    		Console.Write("bool           ");
    		Console.Write(sizeof(bool));
    		Console.WriteLine("  Bytes");
    		Console.Write("int            ");
    		Console.Write(sizeof(int));
    		Console.WriteLine("  Bytes");
    		Console.Write("uint           ");
    		Console.Write(sizeof(uint));
    		Console.WriteLine("  Bytes");
    		Console.Write("short          ");
    		Console.Write(sizeof(short));
    		Console.WriteLine("  Bytes");
    		Console.Write("ushort         ");
    		Console.Write(sizeof(ushort));
    		Console.WriteLine("  Bytes");
    		Console.Write("byte           ");
    		Console.Write(sizeof(byte));
    		Console.WriteLine("  Bytes");
    		Console.Write("sbyte          ");
    		Console.Write(sizeof(sbyte));
    		Console.WriteLine("  Bytes");
    		Console.Write("float          ");
    		Console.Write(sizeof(float));
    		Console.WriteLine("  Bytes");
    		Console.Write("double         ");
    		Console.Write(sizeof(double));
    		Console.WriteLine("  Bytes");
    		Console.Write("decimal        ");
    		Console.Write(sizeof(decimal));
    		Console.WriteLine(" Bytes");
    		Console.Write("long           ");
    		Console.Write(sizeof(long));
    		Console.WriteLine("  Bytes");
    		Console.Write("ulong          ");
    		Console.Write(sizeof(ulong));
    		Console.WriteLine("  Bytes");
    		Console.WriteLine("===========================");
    		Console.WriteLine();
    	}
    }
  2. Save the file in a new folder named MemoryUse1
  3. Save the file itself as Exercise.cs
  4. Open the Command Prompt and change to the MemoryUse1 folder that contains the above Exercise.cs file
  5. To compile it, type csc /unsafe Exercise and press Enter. This would produce:
     
    The sizeof Operator
    ==========================
    Data Type     Memory Size
    --------------------------
    char            2 Bytes
    bool            1 Bytes
    int             4 Bytes
    uint            4 Bytes
    short           2 Bytes
    ushort          2 Bytes
    byte            1 Bytes
    sbyte           1 Bytes
    float           4 Bytes
    double          8 Bytes
    decimal        16 Bytes
    long            8 Bytes
    ulong           8 Bytes
    ===========================
  6. To execute it, type Exercise and press Enter
 

Algebraic Operators

In algebra, operations are performed on numeric values. Algebraic operators are represented with the following symbols:

Operations
 

The Addition

The addition is an operation used to add things of the same nature one to another, as many as necessary. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. The addition is performed in mathematics using the + sign. The same sign is used in C#.

To get the addition of two values, you add the first one to the other. After the addition of two values has been performed, you get a new value. This means that if you add Value1 to Value2, you would write Value1 + Value2. The result is another value we could call Value3. You can also add more than two values, like a + b + c.

With numbers, the order you use to add two or more values doesn't matter. This means that Value1 + Value2 is the same as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a

Here is an example that adds two numbers:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			System.Console.Write("244 + 835 = ");
			System.Console.WriteLine(244 + 835);
		}
	}
}

Here is the result:

244 + 835 = 1079

You can also add some values already declared and initialized in your program. You can also get the values from the user.

In C#, you can also add string variables to add a new string. The operation is performed as if you were using numbers. For example, "Pie" + "Chart" would produce "PieChart". You can also add add as many strings as possible by including the + operator between them. Here is an example:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			string FirstName = "Alexander";
			string LastName  = "Kallack";
			string FullName  = FirstName + " " + LastName;
			System.Console.Write("Full Name: ");
			System.Console.WriteLine(FullName);
		}
	}
}

This would produce:

Full Name: Alexander Kallack

Practical LearningPractical Learning: Using the Addition Operator

  1. Reopen the Exercise.cs file from the GCS2 folder
  2. To use the addition, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			string CustomerName = "James Burreck",
    				   HomePhone = "(202) 301-7030";
    			uint NumberOfShirts   = 1,
    				 NumberOfPants    = 1,
    				 NumberOfDresses  = 1;
    			uint TotalNumberOfItems;
    			decimal PriceOneShirt     = 0.95M,
    				    PriceAPairOfPants = 2.95M,
    				    PriceOneDress     = 4.55M;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    
    			TotalNumberOfItems = NumberOfShirts + NumberOfPants + NumberOfDresses;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("========================");
    			Console.Write("Customer:   ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone: ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Order Date: ");
    			Console.Write(OrderMonth);
    			Console.Write('/');
    			Console.Write(OrderDay);
    			Console.Write('/');
    			Console.WriteLine(OrderYear);
    			Console.WriteLine("------------------------");
    			Console.WriteLine("Item Type  Qty Sub-Total");
    			Console.WriteLine("------------------------");
    			Console.Write("Shirts      ");
    			Console.Write(NumberOfShirts);
    			Console.Write("     ");
    			Console.WriteLine(PriceOneShirt);
    			Console.Write("Pants       ");
    			Console.Write(NumberOfPants);
    			Console.Write("     ");
    			Console.WriteLine(PriceAPairOfPants);
    			Console.Write("Dresses     ");
    			Console.Write(NumberOfDresses);
    			Console.Write("     ");
    			Console.WriteLine(PriceOneDress);
    			Console.WriteLine("------------------------");
    			Console.Write("Number of Items: ");
    			Console.WriteLine(TotalNumberOfItems);
    			Console.WriteLine("========================");
    			Console.WriteLine();
    		}
    	}
    }
  3. Save the file
  4. At the Command Prompt, change to the GCS2 folder
  5. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  6. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      1     0.95
    Pants       1     2.95
    Dresses     1     4.55
    ------------------------
    Number of Items: 3
    ========================
  7. Return to Notepad

The Multiplication

The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: A + A + A + A, since the variable a is repeated over and over again, you could simply find out how many times A is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result.

Just like the addition, the multiplication is associative: a * b * c = c * b * a. When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication.

Here is an example:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// Initializing various variables when declaring them with the same data type
			double Value1 = 224.58, Value2 = 1548.26;
			double Result = Value1 * Value2;
			
			System.Console.Write(Value1);
			System.Console.Write(" * ");
			System.Console.Write(Value2);
			System.Console.Write(" = ");
			System.Console.WriteLine(Result);
			System.Console.WriteLine();
		}
	}
}

This would produce:

224.58 * 1548.26 = 347708.2308

Practical LearningPractical Learning: Using the Multiplication Operator

  1. To multiply, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			const decimal PriceOneShirt     = 0.95M;
    			const decimal PriceAPairOfPants = 2.95M;
    			const decimal PriceOneDress     = 4.55M;
    			string CustomerName = "James Burreck",
    				   HomePhone = "(202) 301-7030";
    			uint NumberOfShirts   = 5,
    				 NumberOfPants    = 2,
    				 NumberOfDresses  = 3;
    			uint TotalNumberOfItems;
    			decimal SubTotalShirts, SubTotalPants, SubTotalDresses;
    			decimal TotalOrder;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    
    			TotalNumberOfItems = NumberOfShirts + NumberOfPants + NumberOfDresses;
    			SubTotalShirts  = PriceOneShirt * NumberOfShirts;
    			SubTotalPants   = PriceAPairOfPants * NumberOfPants;
    			SubTotalDresses = NumberOfDresses * PriceOneDress;
    			TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("====================================");
    			Console.Write("Customer:   ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone: ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Order Date: ");
    			Console.Write(OrderMonth);
    			Console.Write('/');
    			Console.Write(OrderDay);
    			Console.Write('/');
    			Console.WriteLine(OrderYear);
    			Console.WriteLine("------------------------------------");
    			Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    			Console.WriteLine("------------------------------------");
    			Console.Write("Shirts      ");
    			Console.Write(NumberOfShirts);
    			Console.Write("     ");
    			Console.Write(PriceOneShirt);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalShirts);
    			Console.Write("Pants       ");
    			Console.Write(NumberOfPants);
    			Console.Write("     ");
    			Console.Write(PriceAPairOfPants);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalPants);
    			Console.Write("Dresses     ");
    			Console.Write(NumberOfDresses);
    			Console.Write("     ");
    			Console.Write(PriceOneDress);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalDresses);
    			Console.WriteLine("------------------------------------");
    			Console.Write("Number of Items: ");
    			Console.WriteLine(TotalNumberOfItems);
    			Console.Write("Total Order:     ");
    			Console.WriteLine(TotalOrder);
    			Console.WriteLine("====================================");
    			Console.WriteLine();
    		}
    	}
    }
  2. Save the file
  3. At the Command Prompt, change to the GCS2 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    ====================================
  6. Return to Notepad

The Subtraction

The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition. The subtraction is performed with the - sign.

Here is an example:

using System;

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// Values used in this program
			double Value1 = 224.58, Value2 = 1548.26;
			double Result = Value1 - Value2;

			Console.Write(Value1);
			Console.Write(" - ");
			Console.Write(Value2);
			Console.Write(" = ");
			Console.WriteLine(Result);
		}
	}
}

This would produce:

224.58 - 1548.26 = -1323.68

Unlike the addition, the subtraction is not associative. In other words, a - b - c is not the same as c - b - a. Consider the following program that illustrates this:

using System;

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// This tests whether the addition is associative
			Console.WriteLine(" =+= Addition =+=");
			Console.Write("128 + 42 +   5 = ");
			Console.WriteLine(128 + 42 + 5);
			Console.Write("  5 + 42 + 128 = ");
			Console.WriteLine(5 + 42 + 128);

			Console.WriteLine();

			// This tests whether the subtraction is associative
			Console.WriteLine(" =-= Subtraction =-=");
			Console.Write("128 - 42 -   5 = ");
			Console.WriteLine(128 - 42 - 5);
			Console.Write("  5 - 42 - 128 = ");
			Console.WriteLine(5 - 42 - 128);
			
			Console.WriteLine();
		}
	}
}

This would produce:

=+= Addition =+=
128 + 42 +   5 = 175
  5 + 42 + 128 = 175

 =-= Subtraction =-=
128 - 42 -   5 = 81
  5 - 42 - 128 = -165

Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but produce different results.

Practical LearningPractical Learning: Using the Subtraction Operator

  1. To Subtract, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			const decimal PriceOneShirt     = 0.95M;
    			const decimal PriceAPairOfPants = 2.95M;
    			const decimal PriceOneDress     = 4.55M;
    			const decimal SalesTaxRate      = 0.0575M; // 5.75%
    
    			string CustomerName = "James Burreck",
    				   HomePhone = "(202) 301-7030";
    			uint NumberOfShirts   = 5,
    				 NumberOfPants    = 2,
    				 NumberOfDresses  = 3;
    			uint TotalNumberOfItems;
    			decimal SubTotalShirts, SubTotalPants, SubTotalDresses;
    			decimal TaxAmount, TotalOrder, NetPrice;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    
    			TotalNumberOfItems = NumberOfShirts + NumberOfPants + NumberOfDresses;
    			SubTotalShirts  = PriceOneShirt * NumberOfShirts;
    			SubTotalPants   = PriceAPairOfPants * NumberOfPants;
    			SubTotalDresses = NumberOfDresses * PriceOneDress;
    			TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses;
    			TaxAmount = TotalOrder * SalesTaxRate;
    			NetPrice  = TotalOrder - TaxAmount;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("====================================");
    			Console.Write("Customer:   ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone: ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Order Date: ");
    			Console.Write(OrderMonth);
    			Console.Write('/');
    			Console.Write(OrderDay);
    			Console.Write('/');
    			Console.WriteLine(OrderYear);
    			Console.WriteLine("------------------------------------");
    			Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    			Console.WriteLine("------------------------------------");
    			Console.Write("Shirts      ");
    			Console.Write(NumberOfShirts);
    			Console.Write("     ");
    			Console.Write(PriceOneShirt);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalShirts);
    			Console.Write("Pants       ");
    			Console.Write(NumberOfPants);
    			Console.Write("     ");
    			Console.Write(PriceAPairOfPants);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalPants);
    			Console.Write("Dresses     ");
    			Console.Write(NumberOfDresses);
    			Console.Write("     ");
    			Console.Write(PriceOneDress);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalDresses);
    			Console.WriteLine("------------------------------------");
    			Console.Write("Number of Items: ");
    			Console.WriteLine(TotalNumberOfItems);
    			Console.Write("Total Order:     ");
    			Console.WriteLine(TotalOrder);
    			Console.Write("Tax Rate:        ");
    			Console.Write(SalesTaxRate * 100);
    			Console.WriteLine('%');
    			Console.Write("Tax Amount:      ");
    			Console.WriteLine(TaxAmount);
    			Console.Write("Net Price:       ");
    			Console.WriteLine(NetPrice);
    			Console.WriteLine("====================================");
    			Console.WriteLine();
    		}
    	}
    }
  2. Save the file
  3. At the Command Prompt, change to the GCS2 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    Discount Rate:   12.500%
    Discount Amount: 3.03750
    Net Price:       21.26250
    ====================================
  6. Return to Notepad

The Division

Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /.

Here is an example:

namespace Operations
{
	class Exercise
	{
		static void Main()
		{
			// Initializing various variables when declaring them with the same data type
			double Value1 = 224.58, Value2 = 1548.26;
			double Result = Value1 / Value2;
			
			System.Console.Write(Value1);
			System.Console.Write(" / ");
			System.Console.Write(Value2);
			System.Console.Write(" = ");
			System.Console.WriteLine(Result);
			System.Console.WriteLine();
		}
	}
}

This would produce:

224.58 / 1548.26 = 0.145053156446592

When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation.

 

Practical LearningPractical Learning: Using the Division Operator

  1. To use the division, change the file as follows:
     
    using System;
    
    namespace GeorgetownCleaningServices
    {
    	class OrderProcessing
    	{
    		static void Main()
    		{
    			const decimal PriceOneShirt     = 0.95M;
    			const decimal PriceAPairOfPants = 2.95M;
    			const decimal PriceOneDress     = 4.55M;
    			const decimal DiscountRate      = 0.20M; // 20%
    			const decimal TaxRate           = 5.75M;  // 5.75%
    
    			string CustomerName = "James Burreck",
    				   HomePhone = "(202) 301-7030";
    			uint NumberOfShirts   = 5,
    				 NumberOfPants    = 2,
    				 NumberOfDresses  = 3;
    			uint TotalNumberOfItems;
    			decimal SubTotalShirts, SubTotalPants, SubTotalDresses;
    			decimal DiscountAmount, TotalOrder, NetPrice, TaxAmount, SalesTotal;
    			decimal AmountTended, Difference;
    			uint OrderMonth = 3, OrderDay = 15, OrderYear = 2002;
    
    			TotalNumberOfItems = NumberOfShirts + NumberOfPants + NumberOfDresses;
    			SubTotalShirts  = PriceOneShirt * NumberOfShirts;
    			SubTotalPants   = PriceAPairOfPants * NumberOfPants;
    			SubTotalDresses = NumberOfDresses * PriceOneDress;
    			TotalOrder      = SubTotalShirts + SubTotalPants + SubTotalDresses;
    			DiscountAmount  = TotalOrder * DiscountRate;
    			NetPrice        = TotalOrder - DiscountAmount;
    			TaxAmount       = TotalOrder * TaxRate / 100;
    			SalesTotal      = NetPrice + TaxAmount;
    			AmountTended    = 50M;
    			Difference      = AmountTended - SalesTotal;
    
    			Console.WriteLine("-/- Georgetown Cleaning Services -/-");
    			Console.WriteLine("====================================");
    			Console.Write("Customer:   ");
    			Console.WriteLine(CustomerName);
    			Console.Write("Home Phone: ");
    			Console.WriteLine(HomePhone);
    			Console.Write("Order Date: ");
    			Console.Write(OrderMonth);
    			Console.Write('/');
    			Console.Write(OrderDay);
    			Console.Write('/');
    			Console.WriteLine(OrderYear);
    			Console.WriteLine("------------------------------------");
    			Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    			Console.WriteLine("------------------------------------");
    			Console.Write("Shirts      ");
    			Console.Write(NumberOfShirts);
    			Console.Write("     ");
    			Console.Write(PriceOneShirt);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalShirts);
    			Console.Write("Pants       ");
    			Console.Write(NumberOfPants);
    			Console.Write("     ");
    			Console.Write(PriceAPairOfPants);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalPants);
    			Console.Write("Dresses     ");
    			Console.Write(NumberOfDresses);
    			Console.Write("     ");
    			Console.Write(PriceOneDress);
    			Console.Write("     ");
    			Console.WriteLine(SubTotalDresses);
    			Console.WriteLine("------------------------------------");
    			Console.Write("Number of Items: ");
    			Console.WriteLine(TotalNumberOfItems);
    			Console.Write("Total Order:     ");
    			Console.WriteLine(TotalOrder);
    			Console.Write("Discount Rate:   ");
    			Console.Write(DiscountRate * 100);
    			Console.WriteLine('%');
    			Console.Write("Discount Amount: ");
    			Console.WriteLine(DiscountAmount);
    			Console.Write("After Discount:  ");
    			Console.WriteLine(NetPrice);
    			Console.Write("Tax Rate:        ");
    			Console.Write(TaxRate);
    			Console.WriteLine('%');
    			Console.Write("Tax Amount:      ");
    			Console.WriteLine(TaxAmount);
    			Console.Write("Net Price:       ");
    			Console.WriteLine(SalesTotal);
    			Console.WriteLine("====================================");
    			Console.Write("Amount Tended:   ");
    			Console.WriteLine(AmountTended);
    			Console.Write("Difference:      ");
    			Console.WriteLine(Difference);
    			Console.WriteLine("====================================");
    
    			Console.WriteLine();
    		}
    	}
    }
  2. Save the file
  3. At the Command Prompt, change to the GCS2 folder
  4. To compile the program, type 
    csc /out:"Georgetown Cleaning Services".exe Exercise.cs
    and press Enter
  5. To execute the program, type "Georgetown Cleaning Services" and press Enter. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    Discount Rate:   20.00%
    Discount Amount: 4.8600
    After Discount:  19.4400
    Tax Rate:        5.75%
    Tax Amount:      1.39725
    Net Price:       20.83725
    ====================================
    Amount Tended:   50
    Difference:      29.16275
    ====================================
  6. Return to Notepad

The Remainder

The division program above will give you a result of a number with decimal values if you type an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait?

The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5.

Here is an example:

// Program used to perform the remainder operation.
using System;

class Exercise
{
    static void Main()
    {
	int Players = 26;

	// When the game starts, how many players will wait?.
	Console.Write("Out of ");
	Console.Write(Players);
	Console.Write(" players, ");
	Console.Write(26 % 11);
	Console.WriteLine(" players will have to wait when the game starts.\n");
    }
}

This would produce:

Out of 26 players, 4 players will have to wait when the game starts.

C# Language Operators

 

Increment ++

Introduction

We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated in the following example:

// This program studies value incrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of incrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Value = Value + 1;

		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13

C# provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows:

// This program studies value incrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of incrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Value++;

		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

The ++ is a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value:

// This program studies value incrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of incrementing a value");

		Value++;
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Value++;
		Console.Write("Value = ");
		Console.WriteLine(Value);
		
		Value++;
		Console.Write("Value = ");
		Console.WriteLine(Value);
	}
}

This would produce:

Techniques of incrementing a value
Value = 13
Value = 14
Value = 15
 

Pre and Post-Increment

When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:

// This program studies value incrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of incrementing a value");

		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Console.Write("Value = ");
		Console.WriteLine(++Value);
		
		Console.Write("Value = ");
		Console.WriteLine(Value);
	}
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13
Value = 13

When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the increment operator on the right side of the variable:

// This program studies value incrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of incrementing a value");

		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Console.Write("Value = ");
		Console.WriteLine(Value++);
		
		Console.Write("Value = ");
		Console.WriteLine(Value);
	}
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 12
Value = 13

Decrement --

Introduction

When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a value. This operation works as if a value is decremented by 1, as in Value = Value 1:

// This program studies value decrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Value = Value - 1;

		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11

As done to increment, C# provides a quicker way of subtracting 1 from a value. This is done using the decrement operator, that is --. To use the decrement operator, type - on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:

// This program studies value decrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Value--;

		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

Pre-Decrement

Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the decrement operator on the left side of the operand. This is illustrated in the following program:

// This program studies value decrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Console.Write("Value = ");
		Console.WriteLine(--Value);
		
		Console.Write("Value = ");
		Console.WriteLine(Value);
	}
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11
Value = 11

If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:

// This program studies value decrementing
using System;

class Exercise
{
	static void Main()
	{
		int Value = 12;

		Console.WriteLine("Techniques of decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value); 

		Console.Write("Value = ");
		Console.WriteLine(Value--);
		
		Console.Write("Value = ");
		Console.WriteLine(Value);
	}
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 12
Value = 11

Techniques of Incrementing and Decrementing a Variable

It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:

// This program studies value incrementing and decrementing
using System;

class Exercise
{
	static void Main()
	{
		double Value = 12.75;
		double NewValue;

		Console.WriteLine("Techniques of incrementing and decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value);

		NewValue = Value + 2.42;
		
		Console.Write("Value = ");
		Console.WriteLine(NewValue); 
	}
}

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 15.17

The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable.

Sometimes in your program you will not need to keep the original value of the source variable. You may want to permanently modify the value that a variable is holding. In this case you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable.

To add a value to a variable and change the value that the variable is holding, you can combine the assignment = and the addition + operators to produce a new operator as +=

Here is an example:

// This program studies value incrementing and decrementing
using System;

class Exercise
{
	static void Main()
	{
		double Value = 12.75;

		Console.WriteLine("Techniques of incrementing and decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value);

		Value += 2.42;
		
		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

This program produces the same result as the previous. To decrement the value of a variable, instead of the addition, use the subtraction and apply the same technique. In the above program, the variable can have its value decremented by combining the assignment and the subtraction operations on the variable. This is done with the -= operator. Here is an example:

// This program studies value incrementing and decrementing
using System;

class Exercise
{
	static void Main()
	{
		double Value = 12.75;

		Console.WriteLine("Techniques of incrementing and decrementing a value");
		Console.Write("Value = ");
		Console.WriteLine(Value);

		Value -= 2.42;
		
		Console.Write("Value = ");
		Console.WriteLine(Value); 
	}
}

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 10.33

Operator Precedence and Direction

When combining operations in C#, there are two aspects involved: an operator's precedence and its direction. If you ask the compiler to add two numbers, for example 240 + 65, it will execute the operation by adding 240 to 65. In other words, it would read 240, then +, then 65, and evaluate the result. This is considered as operating from left to right: 240 -> + -> 65. This process is referred to as the direction of the operation.

As you will regularly combine operators on your various calculations, each operation is known for how much it "weighs" as compared to other operators. This is known as its precedence. This means that when a certain operator is combined with another, such as a + b * c, or x / y - z, some operators would execute before others, almost regardless of how you write the operation. That's why an operator could be categorized by its level of precedence.

One way you can avoid being concerned by the level of precedence of operator is by using parentheses to tell the compiler how to proceed with the operations, that is, what operation should (must) be performed first. Consider the following algebraic operation:

154 - 12 + 8

The question here is to know whether you want to subtract the addition of 12 and 8 from 154 or you want to add the difference between 154 and 12 to 8. Using parentheses, you can communicate your intentions to the compiler. This is illustrated in the following program:

using System;

class Exercise
{
	static void Main()
	{
		int Operation1 = (154 - 12) + 8;
		int Operation2 = 154 - (12 + 8);

		Console.Write("Examining the effect of the parentheses in an operation");
		Console.Write("\n(154 - 12) + 8 = ");
		Console.Write(Operation1);
		Console.Write("\n154 - (12 + 8) = ");
		Console.Write(Operation2);
		Console.WriteLine();
	}
}

This would produce:

Examining the effect of the parentheses in an operation
(154 - 12) + 8 = 150
154 - (12 + 8) = 134

As you can see, using the parentheses controls how the whole operation would proceed. This difference can be even more accentuated if your operation includes 3 or more operators and 4 or more operands.

 

Previous Copyright 2004 FunctionX, Inc. Next