๐ŸŽ“ A1Learner
๐Ÿ”

C# Numbers

C# numbers are the numeric values a program counts and measures with. Whole numbers use int or long, and decimal numbers use float or double.

Add subtract multiply

Three expressions run on whole numbers. Each print line shows one result.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(6 + 4);
        Console.WriteLine(6 - 4);
        Console.WriteLine(6 * 4);
    }
}

Division two ways

A literal is a value written directly in code. The double literal 5.0 keeps the decimal part in division.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(5 / 2);
        Console.WriteLine(5.0 / 2);
    }
}

Remainder and order

The % sign gives what is left after division. Multiplication runs before addition.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(7 % 3);
        Console.WriteLine(2 + 3 * 4);
    }
}

A long value

This value is too large for an int. The long type holds it with the letter L.

using System;

class Program
{
    static void Main(string[] args)
    {
        long distance = 9000000000L;
        Console.WriteLine(distance);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 14;
        int b = 5;
        Console.WriteLine(a + b);
        Console.WriteLine(a - b);
        Console.WriteLine(a / b);
        Console.WriteLine(14.0 / b);
    }
}

Key points

  • Use + to add two numbers.
  • Use - to subtract one number from another.
  • Use * to multiply two numbers.
  • Integer division drops the decimal part.
  • A double value keeps the decimal part in division.
  • The % sign gives the remainder after division.
  • Multiplication runs before addition in an expression.

In this example, a holds 14 and b holds 5. The first line prints the sum 19. The second line prints the difference 9. The third line prints the whole quotient 2. The last line uses the double literal 14.0 and prints 2.8.

Note

A decimal value with no letter is a double by default.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does the expression 2 + 3 * 4 print?