Integers and floats in C#

In the previous tutorial we looked at how to create variables and work with the string data type in C#. In this tutorial we will look at how to work with the integer and float data types in C# and also how to convert strings to integers or floats using the int.Parse() and float.Parse() methods. You will also learn how to manipulate numbers using arithmetic operators.

Watch the video below or scroll down to see the sample code.

Sample C# code

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Enter two numbers...");
      float num1 = float.Parse(Console.ReadLine ());
      float num2 = float.Parse(Console.ReadLine ());
      Console.WriteLine (num1 + num2);
    }
  }
}

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used number variables (although they can be used for other things too).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5;

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Next tutorial: Conditional programming in C#