C# Program to Add, Subtract, Multiply and Divide Two Numbers

Seven divided by two is 3 in C#, not 3.5. That surprise is why a C# program to add two numbers, then subtract, multiply and divide them, deserves more than one line. The core is simple: add with + and store the result.

int sum = a + b;

In this tutorial, I’ll start with a C# program to add two numbers and grow it into a small receipt calculator: all five operators, the integer division trap, remainders, divide by zero, overflow, decimal money math and a calculator built on a switch expression.

Here’s where we’re headed, the Step 6 total for an Austin, Texas order with 8.25% sales tax:

Subtotal:    $72.48
Tax 8.25%:    $5.98
Total:       $78.46

Step 1: Write a C# Program to Add, Subtract, Multiply and Divide Two Numbers

Each step is a .NET 10 file-based app you run with dotnet run AddTwoNumbers.cs. Want a full project instead? Here’s how to create a console application in VS Code. My first file adds 7 and 2, then runs the other four operators on them:

int a = 7, b = 2;

int sum = a + b;
Console.WriteLine($"Sum of {a} and {b}: {sum}");

Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{a} - {b} = {a - b}");
Console.WriteLine($"{a} * {b} = {a * b}");
Console.WriteLine($"{a} / {b} = {a / b}");
Console.WriteLine($"{a} % {b} = {a % b}");

Output:

Sum of 7 and 2: 9
7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3
7 % 2 = 1
C# program to add, subtract, multiply and divide two numbers, AddTwoNumbers.cs code and output in VS Code
All five arithmetic operators on 7 and 2

a and b are plain C# variables of type int, and the $"..." string drops each result into your text. % is the remainder, what’s left after /.

Checkpoint: you’ve got a working program. But look at 7 / 2 = 3. That’s not a typo.

Step 2: Why Does 7 / 2 Return 3 When You Divide Two Ints in C#?

When both sides of / are integers, C# does integer division and rounds the result toward zero. To get 3.5, at least one operand has to be double or decimal before the division happens:

int a = 7, b = 2;

Console.WriteLine($"a / b             = {a / b}");
Console.WriteLine($"(double)a / b     = {(double)a / b}");
Console.WriteLine($"a / 2.0           = {a / 2.0}");
Console.WriteLine($"(decimal)a / b    = {(decimal)a / b}");
Console.WriteLine($"(double)(a / b)   = {(double)(a / b)}");

// Splitting a $7 tip between 2 servers
int tipDollars = 7, servers = 2;
double each = tipDollars / servers;
Console.WriteLine($"Each server gets  = {each}");

Output:

a / b             = 3
(double)a / b     = 3.5
a / 2.0           = 3.5
(decimal)a / b    = 3.5
(double)(a / b)   = 3
Each server gets  = 3
C# integer division 7 / 2 returns 3, while (double)a / b, a / 2.0 and (decimal)a / b return 3.5, VS Code output
Casting before the division gives 3.5; casting after it still gives 3

Watch the last two lines. (double)(a / b) casts after the division, so your fraction is already gone. Storing tipDollars / servers in a double doesn’t help either, because the right side is all int.

So each server gets $3 and a dollar disappears. I cover the formatting side in converting an int to a double with 2 decimal places.

Step 3: Get the Remainder of Two Numbers with % and Math.DivRem

The % operator returns what’s left after integer division. Its sign follows the left operand, so -7 % 3 is -1, not 2. When you need both parts, Math.DivRem returns them together:

Console.WriteLine($" 7 %  3 = {7 % 3}");
Console.WriteLine($"-7 %  3 = {-7 % 3}");
Console.WriteLine($" 7 % -3 = {7 % -3}");
Console.WriteLine($"-7 / 3  = {-7 / 3}");

// 17 cupcakes packed in boxes of 6
var (boxes, left) = Math.DivRem(17, 6);
Console.WriteLine($"DivRem(17, 6): {boxes} full boxes, {left} left over");

int n = 42;
Console.WriteLine($"{n} is {(n % 2 == 0 ? "even" : "odd")}");

Output:

 7 %  3 = 1
-7 %  3 = -1
 7 % -3 = 1
-7 / 3  = -2
DivRem(17, 6): 2 full boxes, 5 left over
42 is even

The tuple overload, Math.DivRem(17, 6), arrived in .NET 6. If you’re on .NET Framework, use Math.DivRem(17, 6, out int rem) instead. Both throw DivideByZeroException when the divisor is 0.

n % 2 == 0 is the classic even/odd test, and n % 10 peels off a last digit, the trick behind how you reverse a number with a for loop.

Step 4: Divide by Zero in C#: int Throws, double Returns Infinity

Integer and decimal division by zero throw an exception, but double never does. It quietly returns infinity or NaN:

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

double x = 7.0, zero = 0.0;
Console.WriteLine($"7.0 / 0.0  = {x / zero}");
Console.WriteLine($"-7.0 / 0.0 = {-x / zero}");
Console.WriteLine($"0.0 / 0.0  = {zero / zero}");
Console.WriteLine($"IsInfinity: {double.IsInfinity(x / zero)}");

int orders = 7, days = 0;
try
{
    Console.WriteLine(orders / days);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"int: {ex.GetType().Name}: {ex.Message}");
}

Output:

7.0 / 0.0  = ∞
-7.0 / 0.0 = -∞
0.0 / 0.0  = NaN
IsInfinity: True
int: DivideByZeroException: Attempted to divide by zero.
C# divide by zero: double 7.0 / 0.0 prints infinity and 0.0 / 0.0 prints NaN, while int throws DivideByZeroException, VS Code output
double gives infinity and NaN; int throws DivideByZeroException

Notice that .NET 10 prints the ∞ symbol, not the word Infinity, under en-US. Don’t compare that text; check double.IsInfinity or double.IsNaN instead.

For the int case, a try-catch block in C# works, but checking the divisor first is cleaner. My guide to the C# division by zero exception goes deeper.

Step 5: Catch Overflow When You Add or Multiply Large Numbers

An int tops out at 2,147,483,647. Go one past it and, by default, C# wraps around to a negative number without any warning:

int max = int.MaxValue;
Console.WriteLine($"int.MaxValue      = {max}");
Console.WriteLine($"int.MaxValue + 1  = {max + 1}");

try
{
    int next = checked(max + 1);
}
catch (OverflowException ex)
{
    Console.WriteLine($"checked: {ex.Message}");
}

Output:

int.MaxValue      = 2147483647
int.MaxValue + 1  = -2147483648
checked: Arithmetic operation resulted in an overflow.

With checked(...) or the CheckForOverflowUnderflow project setting, the same addition throws OverflowException. If your totals can get that big, use long.

This wraparound also breaks the trick to swap two numbers in C# with addition and subtraction.

Step 6: Use decimal to Add Prices and Sales Tax

Here’s the receipt from the top. First, though, see why double is wrong for your money math: it stores 0.1 and 0.2 in binary, so their sum isn’t exactly 0.3.

using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");

Console.WriteLine($"double:  0.1 + 0.2 = {0.1 + 0.2:R}");
Console.WriteLine($"decimal: 0.1 + 0.2 = {0.1m + 0.2m}");

// Austin, TX order: two items, 8.25% sales tax
decimal headphones = 59.99m, cable = 12.49m;
decimal subtotal = headphones + cable;
decimal tax = Math.Round(subtotal * 0.0825m, 2, MidpointRounding.AwayFromZero);
decimal total = subtotal + tax;

Console.WriteLine($"Subtotal: {subtotal,9:C}");
Console.WriteLine($"Tax 8.25%:{tax,9:C}");
Console.WriteLine($"Total:    {total,9:C}");

Output:

double:  0.1 + 0.2 = 0.30000000000000004
decimal: 0.1 + 0.2 = 0.3
Subtotal:    $72.48
Tax 8.25%:    $5.98
Total:       $78.46
C# decimal vs double: 0.1 + 0.2 is 0.30000000000000004 as double and 0.3 as decimal, plus a receipt with 8.25% sales tax, VS Code output
decimal adds 0.1 and 0.2 exactly and prices the receipt to the cent

The m suffix makes a literal decimal. Tax is $72.48 times 0.0825, which is 5.9796, so Math.Round with AwayFromZero makes it $5.98.

I set en-US culture at the top so :C prints dollars on your PC too. To go further, see how to format a number with commas and decimals in C# or read my overview of data types in C#.

Step 7: Build a Calculator Program with a switch Expression and int.TryParse

The last step turns the operators into a tiny calculator. Input arrives as text, so int.TryParse checks it without throwing, and a switch expression picks the operator.

I feed it string inputs in code here, so you can see six cases in one run:

string[] tests = ["120 + 35", "120 * 3", "7 / 2",
                  "7 / 0", "abc + 5", "9 ^ 2"];
foreach (var t in tests)
    Console.WriteLine($"{t} -> {Run(t.Split(' '))}");
static string Run(string[] p)
{
    if (!int.TryParse(p[0], out int a) || !int.TryParse(p[2], out int b))
        return "Please enter whole numbers.";
    return p[1] switch
    {
        "/" or "%" when b == 0 => "Can't divide by zero.",
        "+" => $"{a + b}",
        "-" => $"{a - b}",
        "*" => $"{a * b}",
        "/" => $"{(double)a / b}",
        "%" => $"{a % b}",
        _ => $"Unknown operator '{p[1]}'",
    };
}

Output:

120 + 35 -> 155
120 * 3 -> 360
7 / 2 -> 3.5
7 / 0 -> Can't divide by zero.
abc + 5 -> Please enter whole numbers.
9 ^ 2 -> Unknown operator '^'
C# calculator program using a switch expression on the operator and int.TryParse for input validation, six test cases in VS Code
One switch expression handles +, -, *, / and %, plus bad input and divide by zero

Each "+" => ... arm returns a value, tighter than the old switch case statement in C# with a break after every case. _ catches the rest.

The when b == 0 arm comes first, so it guards both / and %. Prefer one method per operator? See functions in C#.

Checkpoint: you now have a calculator that can’t crash on bad input, a zero divisor or an unknown operator.

Which Numeric Type Should You Use for Arithmetic in C#?

TypeUse it forWatch out for
intCounts, quantities, IDs7 / 2 = 3, overflow past 2.1 billion
longLarge counts and totalsSame integer division rules
doubleMeasurements, science, averages0.1 + 0.2 isn’t exact; / 0 gives ∞
decimalPrices, tax, anything in USDSlower, throws on / 0

My rule: int until there’s a fraction, decimal the moment there’s a dollar sign. To parse user-typed amounts, read about how to convert a string to double in C#.

Ready for the next number exercise? Try one of these:

Frequently Asked Questions

How do I add two numbers entered by the user in C#?

Read each value with Console.ReadLine(), convert it with int.TryParse(input, out int a), then add: int sum = a + b;. TryParse returns false instead of throwing if you type something that isn’t a number.

How do I divide two ints and get a decimal result in C#?

Cast one operand first: (double)a / b or (decimal)a / b. 7 / 2 gives 3, but (double)7 / 2 gives 3.5.

Why is -7 % 3 equal to -1 in C#?

The sign of a non-zero remainder matches the left operand, as described in the C# arithmetic operators reference on Microsoft Learn. For a result that’s always positive, use ((a % n) + n) % n.

Should I use double or decimal to add prices in C#?

Use decimal. double can’t store most cent values exactly, so 0.1 + 0.2 prints 0.30000000000000004. decimal gives 0.3.

Does dividing a double by zero throw an exception in C#?

No. double and float return positive or negative infinity, or NaN for 0.0 / 0.0. Only integer and decimal division by zero throw DivideByZeroException.