Lesson Weekend

Let’s look at another common data type: integers. Integers represent whole numbers (that is, numbers without decimals). C# integers are similar to the JavaScript integers we used in Intro.

Integers


We'll practice working with integers in the REPL. Let's open our REPL with the $ dotnet-script command in the Terminal (for Mac) or GitBash (for Windows).

Now we can create a new integer like this:

> 1
1

Easy enough! But do notice this is very different than:

> "1"
"1"

The second example is a string containing an integer. Strings are the only type of data wrapped in quotation marks. If we put quotation marks around a number, it's actually a string...and will act as such!

For instance, check out what happens when we add two numbers wrapped in quotations:

> "1" + "1"
"11"

1 + 1 isn't 11! But we receive this result because the REPL is actually concatenating two strings containing the character 1 together. You likely already recognize this type of error from JavaScript but it's so common it's worth mentioning again!

We can avoid this erroneous math by avoiding quotation marks and ensuring numerical values are integers like this:

> 1 + 1
2

That's more like it!

Arithmetic Operators

The four arithmetic operators we used in JavaScript work the same in C#. You should recall these basic operators:

  • + for addition, as seen in the example above.
  • - for subtraction.
  • * for multiplication.
  • / for division.

We can use each with integers in the REPL and receive expected results:

Subtraction:

> 1 - 1
0

Addition:

> 1 + 1
2

Multiplication:

> 2 * 2
4

Division:

> 4 / 2
2

Modulo:

> 5 % 2
1

As we discussed in Intro to Programming, a modulo gives us the remainder of dividing two numbers. It doesn't have anything to do with percentages!

Terminology


  • Integers: A type of data representing whole numbers (numbers without decimals).

  • Operators: A special character (or characters) that indicates an action to be performed.+, -, *, /, and % are all operators for mathematic functions.

Examples


Basic arithmetic works just like you'd expect:

1 + 2
4 - 3
5 * 6
9 / 2
7 + 8 * 9
(7 + 8) * 9

Overview


  • 9 % 2 returns the remainder of 9 divided by 2. % is called modulo.

Lesson 3 of 5
Last updated more than 3 months ago.