C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
Arithmetic Operations - Example
This section provides a tutorial example on how to use arithmetic operations: Multiplication, Division, Addition, and Subtraction.
Now let's practice what we have learned so far with a simple program to simulate the cash register in a grocery store:
// Cashier.cs
// Copyright (c) 2006 HerongYang.com. All Rights Reserved.
class Cashier {
public static void Main() {
long qty_milk, qty_bread, qty_coke;
double price_milk, price_bread, price_coke;
double total;
qty_milk = 2;
qty_bread = 1;
qty_coke = 6;
price_milk = 1.99;
price_bread = 1.49;
price_coke = 0.99;
total = qty_milk * price_milk;
total = total + qty_bread * price_bread;
total = total + qty_coke * price_coke;
System.Console.WriteLine("Receipt");
System.Console.WriteLine(" ");
System.Console.WriteLine(
"Product Price Quantity Sub-total");
System.Console.WriteLine(
"Mike 2% 2L {0} {1} {2}",
price_milk, qty_milk, qty_milk*price_milk);
System.Console.WriteLine(
"Bread 1lb {0} {1} {2}",
price_bread, qty_bread, qty_bread*price_bread);
System.Console.WriteLine(
"Coke 2L {0} {1} {2}",
price_coke, qty_coke, qty_coke*price_coke);
System.Console.WriteLine(" ");
System.Console.WriteLine(
"Total: {0}",
total);
}
}
Output of the program will be:
Receipt Product Price Quantity Sub-total Mike 2% 2L 1.99 2 3.98 Bread 1lb 1.49 1 1.49 Coke 2L 0.99 6 5.94 Total: 11.41
Notice that how the space characters are used in the WriteLine method call to line the columns in the output.
Exercise: Modify the Cashier class to add tax into the calculation, assuming the tax rate is 5%. Tax must be applied on the total price. The tax amount must be printed out on a separate line.
Table of Contents
Variables and Assignment Statements
Variables and Assignments - Example
►Arithmetic Operations - Example
Logical Expressions and Conditional Statements
Visual C# 2010 Express Edition
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation