Post

C# - Working with numbers

Performing addition with implicit data conversion

  • In C#, you can perform arithmetic operations on numeric data types.
  • When you perform arithmetic operations on different data types, C# will automatically convert the data types to a common type.
  • For example, consider the following code:
1
2
3
4
5
6
7
int myInt = 5;
double myDouble = 2.5;

Console.WriteLine(myInt + myDouble);

// Output:
// 7.5

Mix data types to force implicit type conversions

  • You can mix data types to force implicit type conversions.
  • For example, consider the following code:
1
2
3
4
5
6
string firstName = "Mark";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + widgetsSold + " widgets.");

// Output:
// Mark sold 7 widgets.
  • In this case, the C# compiler understands that you want to use the + symbol to concatenate the two operands.
  • It deduces this because the + symbol is surrounded by operands of string and int data types. So, it attempts to implicitly convert the int variable widgetsSold into a string temporarily so it can concatenate it to the rest of the string.
  • The C# compiler tries to help you when it can, but ideally, you would be explicit about your intentions.

A more advanced case of adding numbers and concatenating strings

  • Consider the following code:
1
2
3
4
5
6
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + widgetsSold + 7 + " widgets.");

// Output:
// Bob sold 77 widgets.
  • In this case, the C# compiler interprets the + symbol as an addition operator for the first two operands.
  • After the first two operands are added, the C# compiler then interprets the + symbol as a concatenation operator for the remaining operands.
  • This is because the first two operands are of the string and int data types, and the remaining operands are all integers.
  • To avoid this confusion, you can use parentheses to group the operands:
1
2
3
4
5
6
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + (widgetsSold + 7) + " widgets.");

// Output:
// Bob sold 14 widgets.

Basic arithmetic operators

  • C# provides several arithmetic operators for performing basic arithmetic operations.
  • The following table lists the arithmetic operators available in C#:
    • + (addition)
    • - (subtraction)
    • * (multiplication)
    • / (division)
    • % (modulus)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int sum = 7 + 5;
int difference = 7 - 5;
int product = 7 * 5;
int quotient = 7 / 5;

Console.WriteLine("Sum: " + sum);
Console.WriteLine("Difference: " + difference);
Console.WriteLine("Product: " + product);
Console.WriteLine("Quotient: " + quotient);

// Output:
// Sum: 12
// Difference: 2
// Product: 35
// Quotient: 1

Perform division using literal decimal data

  • When you perform division using literal decimal data, the result will be a decimal.
  • For example, consider the following code:
1
2
3
4
5
decimal decimalQuotient = 7.0m / 5;
Console.WriteLine($"Decimal quotient: {decimalQuotient}");

// Output:
// Decimal quotient: 1.4
  • For this to work, the quotient (left of the assignment operator) must be of type decimal and at least one of numbers being divided must also be of type decimal (both numbers can also be a decimal type).
1
2
3
4
5
decimal decimalQuotient = 7 / 5.0m;
decimal decimalQuotient = 7.0m / 5.0m;

// Output:
// Decimal quotient: 1.4
  • However, the following lines of code won’t work (or give inaccurate results):
1
2
3
4
int decimalQuotient = 7 / 5.0m;
int decimalQuotient = 7.0m / 5;
int decimalQuotient = 7.0m / 5.0m;
decimal decimalQuotient = 7 / 5;

Perform division with casting

  • What if you are not working with literal values?
  • In other words, what if you need to divide two variables of type int but do not want the result truncated? In that case, you must perform a data type cast from int to decimal.
  • Casting is one type of data conversion that instructs the compiler to temporarily treat a value as if it were a different data type.
  • To cast int to decimal, you add the cast operator before the value.
  • You use the name of the data type surrounded by parentheses in front of the value to cast it.
  • In this case, you would add (decimal) before the variables first and second.
1
2
3
4
int first = 7;
int second = 5;
decimal quotient = (decimal)first / (decimal)second;
Console.WriteLine(quotient);

The modulus operator

  • The modulus operator (%) returns the remainder of a division operation.
  • This can be useful during long processing operations when looping through hundreds or thousands of data records and you want to provide feedback to the end user after every 100 data records have been processed.
  • When the modulus is 0, that means the dividend is divisible by the divisor.
1
2
3
4
5
6
Console.WriteLine($"Modulus of 200 / 5 : {200 % 5}");
Console.WriteLine($"Modulus of 7 / 5 : {7 % 5}");

// Output:
// Modulus of 200 / 5 : 0
// Modulus of 7 / 5 : 2

Order of operations in C#

In math, PEMDAS is an acronym that helps students remember the order of operations. The order is:

  • Parentheses (whatever is inside the parenthesis is performed first)
  • Exponents
  • Multiplication and Division (from left to right)
  • Addition and Subtraction (from left to right)

C# follows the same order as PEMDAS except for exponents.

  • What will be the output of the following code?
1
2
int result = 3 + 1 * 5 / 2;
Console.WriteLine(result);
  • I thought the answer would be 5.5, but it’s 5. Why?
  • The answer is 5 because C# follows the order of operations.
  • The multiplication and division operators have the same precedence, so they are evaluated from left to right.
  • The multiplication operator is evaluated first, so 1 * 5 is calculated first, which equals 5.
  • Then, the division operator is evaluated, so 5 / 2 is calculated, which equals 2.5, but since the result is an integer, the decimal part is truncated.
  • Finally, the addition operator is evaluated, so 3 + 2 is calculated, which equals 5.

Increment and decrement

  • The increment and decrement operators are used to increase or decrease the value of a variable by 1.
  • They work the same as in other programming languages.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int value = 1;

value = value + 1;
Console.WriteLine("First increment: " + value);

value += 1;
Console.WriteLine("Second increment: " + value);

value++;
Console.WriteLine("Third increment: " + value);

value = value - 1;
Console.WriteLine("First decrement: " + value);

value -= 1;
Console.WriteLine("Second decrement: " + value);

value--;
Console.WriteLine("Third decrement: " + value);

Use the increment operator before and after the value

1
2
3
4
5
6
int value = 1;
value++;
Console.WriteLine("First: " + value);
Console.WriteLine($"Second: {value++}");
Console.WriteLine("Third: " + value);
Console.WriteLine("Fourth: " + (++value));
  • consider the last line of code: Console.WriteLine("Fourth: " + (++value));
  • The ++ operator is placed before the variable name, which means the value is incremented before it is used in the expression.
This post is licensed under CC BY 4.0 by the author.