ms_learn_csharp/004_Basic_operation_on_numbers/004_csharp.md

580 lines
17 KiB
Markdown
Raw Normal View History

2024-07-17 16:32:54 -04:00
# Basic number operations
### Introduction
The applications you'll build in C# will require that you operate on literal
and variable numeric data. Examples might include:
- Performing simple mathematical operations including addition, subtraction,
multiplication, and division
- Performing multi-step operations that must be completed in a certain order
- Determining the remainder after performing division
- Incrementing or decrementing a value, and so on
Suppose you want to perform a calculation that converts a value from one unit
of measure to another. For example, what if you needed to convert the current
temperature from Fahrenheit to Celsius? Once you've calculated the temperature
in degrees Celsius, you need to display that information in a formatted
message to the user. To accomplish this, you'll need to learn to use operators
to act on operands like literal and variable values.
In this module, you'll perform basic string and numeric operations on your data.
As you'll learn, the compiler will perform different tasks depending on the
data types of the values around the given operator. More importantly, you'll
come to understand how operators perform actions on operands. Learning how to
work with operators and operands correctly will help you formulate meaningful
instructions in your code.
By the end of this module, you will be able to write code that performs basic
operations on literal and variable values.
### Learning objectives
In this module, you will:
- Perform mathematical operations on numeric values
- Observe implicit type conversion between strings and numeric values
- Temporarily convert one data type into another
#### Prerequisites
- Beginner level experience with a .NET editor
- Beginner level experience with basic C# syntax rules
- Beginner level experience with displaying a message to a console using the
`Console.WriteLine` and `Console.Write` methods
- Beginner level experience with creating literal values and declare variables
of basic data types like string, int, and decimal
- Beginner level experience with string concatenation and string interpolation
---
## Exercise
### Perform addition with implicit data conversion
Often, you'll want to perform mathematical operations on numeric data. You'll
start with addition in this unit, and expand to other operations in the next
unit because there's an important lesson to learn about how the C# compiler
parses and interprets your code.
#### Add two numeric values
To add two numbers together, you'll use the addition operator, which is the
plus symbol `+`. Yes, the same plus symbol + that you use for string
concatenation is also used for addition. The reuse of one symbol for multiple
purposes is sometimes called "overloading the operator" and happens frequently
in C#.
In this instance, the C# compiler understands what you're attempting to do.
The compiler parses your code and sees that the `+` (the operator) is surrounded
by two numeric values (the operands). Given the data types of the variables
(both are ints), it figures out that you intended to add those two values.
Enter the following code into the .NET Editor:
```cs
int firstNumber = 12;
int secondNumber = 7;
Console.WriteLine(firstNumber + secondNumber);
```
Run the code and you'll see the following result in the output console:
Output
```txt
19
```
Mix data types to force implicit type conversions
What happens if you try to use the + symbol with both string and int values?
Modify the code you wrote to match the following code:
```cs
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + widgetsSold + " widgets.");
```
Run the code and you'll see the following result in the output console:
Output
```txt
Bob 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.
Attempt a more advanced case of adding numbers and concatenating strings
Modify the code you wrote to match the following code:
```cs
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + widgetsSold + 7 + " widgets.");
```
Run the code and you'll see the following result in the output console:
Output
```txt
Bob sold 77 widgets.
```
Instead of adding the int variable widgetsSold to the literal int 7, the
compiler treats everything as a string and concatenates it all together.
Add parentheses to clarify your intention to the compiler
Modify the code you wrote to match the following code:
```cs
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + (widgetsSold + 7) + " widgets.");
```
Run the code and you'll see the following result in the output console:
Output
```txt
Bob sold 14 widgets.
```
The parentheses symbol `()` becomes another overloaded operator. In this case,
the opening and closing parentheses form the order of operations operator,
just like you might use in a mathematical formula. You indicate that you want
the inner-most parentheses resolved first resulting in the addition of int
values widgetsSold and the value 7. Once that is resolved, then it will
implicitly convert the result to a string so that it can be concatenated with
the rest of the message.
> Note
> You should probably avoid performing both a calculation and concatenation in
a single line of code. The point here is to help you understand how to view
operators and operands the way the compiler does.
### Recap
Here's what you've learned so far about mathematical operations in C#:
- You can perform mathematical-like addition operations on numbers.
- Both string concatenation and addition use the plus + symbol. This is called
overloading an operator, and the compiler infers the proper use based on the
data types it's operating on.
- When it can, the C# compiler will implicitly convert an int into a string if
it's obvious that the developer is trying to concatenate the string
representation of a number for presentation purposes.
- Use parentheses to define an order of operations to explicitly tell the
compiler that you want to perform certain operations before other operations.
---
## Exercise
### Perform math operations
Now that you understand the basics of addition and more importantly, implicit
type conversion between numeric and string data types, let's look at several
other common mathematical operations on numeric data.
#### Perform basic math operations
Write code to perform addition, subtraction, multiplication, and division with
integers
Enter the following code in the .NET Editor:
```cs
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);
```
Run the code. You should see the following output:
Output
```txt
Sum: 12
Difference: 2
Product: 35
Quotient: 1
```
As you can see:
- `+` is the addition operator
- `-` is the subtraction operator
- `*` is the multiplication operator
- `/` is the division operator
However, the resulting quotient of the division example may not be what you
may have expected. The values after the decimal are truncated from the
quotient since it is defined as an `int`, and `int` cannot contain values after
the `decimal`.
#### Add code to perform division using literal decimal data
To see division working properly, you need to use a data type that supports
fractional digits after the decimal point like decimal.
```cs
decimal decimalQuotient = 7.0m / 5;
Console.WriteLine($"Decimal quotient: {decimalQuotient}");
```
Run the code. You should see the following output:
Output
```txt
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).
Here are two additional examples that work equally well:
```cs
decimal decimalQuotient = 7 / 5.0m;
decimal decimalQuotient = 7.0m / 5.0m;
```
However, the following lines of code won't work (or give inaccurate results):
```cs
int decimalQuotient = 7 / 5.0m;
int decimalQuotient = 7.0m / 5;
int decimalQuotient = 7.0m / 5.0m;
decimal decimalQuotient = 7 / 5;
```
#### Add code to cast results of integer division
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`.
```cs
int first = 7;
int second = 5;
decimal quotient = (decimal)first / (decimal)second;
Console.WriteLine(quotient);
```
Run the code. You should see the following output:
Output
```txt
1.4
```
> Note
> You've seen three uses for the parenthesis operator: method invocation, order
of operations and casting.
Write code to determine the remainder after integer division
The modulus operator % tells you the remainder of int division. What you
really learn from this is whether one number is divisible by another. 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.
```cs
Console.WriteLine($"Modulus of 200 / 5 : {200 % 5}");
Console.WriteLine($"Modulus of 7 / 5 : {7 % 5}");
```
Run the code. You should see the following output:
Output
```txt
Modulus of 200 / 5 : 0
Modulus of 7 / 5 : 2
```
When the modulus is 0, that means the dividend is divisible by the divisor.
### Order of operations
As you learned in the previous exercise, you can use the `()` symbols as
the order of operations operators. However, this isn't the only way the order
of operations is determined.
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. While there's no
exponent operator in C#, you can use the System.Math.Pow method. The module
"Call methods from the .NET Class Library using C#" will feature this method
and others.
#### Write code to exercise C#'s order of operations
```cs
int value1 = 3 + 4 * 5;
int value2 = (3 + 4) * 5;
Console.WriteLine(value1);
Console.WriteLine(value2);
```
Here you see the difference when performing the same operations in a different
order.
Run the code. You should see the following output:
Output
```txt
23
35
```
### Recap
Here's what you've learned so far about mathematical operations in C#:
- Use operators like `+`, `-`, `*`, and `/` to perform basic mathematical
operations.
- The division of two int values will result in the truncation of any values
after the decimal point. To retain values after the decimal point, you need to
cast the divisor or dividend (or both) from int into a floating point number
like decimal first, then the quotient must be of the same floating point type
as well in order to avoid truncation.
- Perform a cast operation to temporarily treat a value as if it were a
different data type.
- Use the % operator to capture the remainder after division.
- The order of operations will follow the rules of the acronym PEMDAS.
---
## Exercise
### Increment and decrement values
The final basic operations you'll learn about in this module is how to
increment and decrement values using special operators that are combinations
of symbols.
### Increment and decrement
Frequently, you'll need to increment and/or decrement values, especially when
you're writing looping logic or code that interacts with a data structure.
The `+=` operator adds and assigns the value on the right of the operator to
the value on the left of the operator. So, lines two and three in the
following code snippet are the same:
```cs
int value = 0; // value is now 0.
value = value + 5; // value is now 5.
value += 5; // value is now 10.
```
The `++` operator increments the value of the variable by 1. So, lines two and
three in the following code snippet are the same:
```cs
int value = 0; // value is now 0.
value = value + 1; // value is now 1.
value++; // value is now 2.
```
These same techniques can be used for subtraction, multiplication, and more.
The following exercise steps will highlight a few.
> Note
> Operators like `+=`, `-=`, `*=`, `++`, and `--` are known as compound
assignment operators because they compound some operation in addition to
assigning the result to the variable. The `+=` operator is specifically termed
the addition assignment operator.
### Write code to increment and decrement a value
Enter the following code in the .NET Editor:
```cs
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);
```
Run the code. You should see the following output:
```txt
First increment: 2
Second increment: 3
Third increment: 4
First decrement: 3
Second decrement: 2
Third decrement: 1
```
> Note
> In the "second increment", you used value `+= 1;`. However you could have
used any literal int value (or a variable) to increment that amount. The same
holds true for the "second decrement": value `-= 1;`.
### Position the increment and decrement operators
Both the increment and decrement operators have an interesting quality —
depending on their position, they perform their operation before or after they
retrieve their value. In other words, if you use the operator before the value
as in `++value`, then the increment will happen before the value is retrieved.
Likewise, `value++` will increment the value after the value has been retrieved.
#### Use the increment operator before and after the value
```cs
int value = 1;
value++;
Console.WriteLine("First: " + value);
Console.WriteLine($"Second: {value++}");
Console.WriteLine("Third: " + value);
Console.WriteLine("Fourth: " + (++value));
```
Run the code. You should see the following output:
Output
```txt
First: 2
Second: 2
Third: 3
Fourth: 4
```
Notice this line of code:
```cs
Console.WriteLine($"Second: {value++}");
```
There's two steps to this line:
- Retrieve the current value of the variable value and use that in the string
interpolation operation.
- Increment the value.
The next line of code confirms that the value was, in fact, incremented.
```cs
Console.WriteLine("Third: " + value);
```
In contrast, consider the last line of code:
```cs
Console.WriteLine("Fourth: " + (++value));
```
Here, the order of operations is switched because the `++` operator is placed
before the operand `value`.
- Increment the value.
- Retrieve the new incremented value of the variable `value` and use that in
the string operation.
While not strictly necessary, you added parenthesis around the expression
(`++value`) to improve readability. Seeing so many `+` operators next to each
other seems like it could be misunderstood by other developers. Stylistic
decisions like this are subjective. However, since you'll write the code once
but read it many times, you should prioritize readability.
### Recap
Here's what you've learned so far about mathematical operations in C#:
- Use compound assignment operators like `+=`, `-=`, `*=`, `++`, and `--` to
perform a mathematical operation like increment or decrement, then assign the
result into the original variable.
- Increment and decrement operators perform differently depending on whether
the operator is before or after the operand.
---
## Complete the challenge to convert Fahrenheit to Celsius
In this challenge, you'll write code that will use a formula to convert a
temperature from degrees Fahrenheit to Celsius. You'll print the result in a
formatted message to the user.
### Challenge
Calculate Celsius given the current temperature in Fahrenheit
Enter the following code in the .NET Editor:
```cs
int fahrenheit = 94;
```
To convert temperatures in degrees Fahrenheit to Celsius, first subtract 32,
then multiply by five ninths (5 / 9).
Display the result of the temperature conversion in a formatted message
Combine the variables with literal strings passed into a series of
`Console.WriteLine()` commands to form the complete message.
When you're finished, the message should resemble the following output:
Output
```txt
The temperature is 34.444444444444444444444444447 Celsius.
```
> Note
> Admittedly, it is preferred to not see so many values after the decimal point.
Ideally the value would be formatted to a single value after the decimal point:
34.4.