Tip Calculator

.C# Tip Calculator

Tip Calculator Program Output

.Tip Calculator

"A C# program to illustrate the following: ternary conditional operator (?:), converting strings to numeric values (TryParse), formatting numeric strings (currency, percentage) , post-test loop (Do-While), string concatenation (+), and method calls (promptUser)."

The Tip Calculator prompts the user using a method which loops until a valid double value is entered for the purchase amount. The same method is called again to obtain a tip percentage. The tip is calculated based on the purchase amount and the percentage. The tip amount is displayed in red. The following C# features are used in the sample code:

  1. ?: - Ternary Conditional Operator
  2. TryParse - Convert Strings to Numeric Values
  3. Standard numeric Format Strings - Format Numeric Strings
  4. Do-While Loop - Post-test Loop
  5. + - String Concatenation
  6. StringBuilder Class - High Performance String Concatenation
  7. Methods - Methods (C# Programming Guide)

Tip Calculator

using System;

namespace TipCalculator
    class Program
        static void Main(string[] args)
            double purchaseAmount = promptUser("purchase amount (e.g. 22.95): ");
            double tipPercentage = promptUser("tipPercentage (e.g. 15.00): ");
            Console.WriteLine("Purchase amount is: {0:C}\n\n", purchaseAmount);
            Console.WriteLine("Tip percentage is: {0:P}\n\n", tipPercentage * 0.01);
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Tip amount is: {0:C}\n\n", purchaseAmount * tipPercentage * 0.01);
            Console.WriteLine("Press any key to exit.");

        /* Prompt Until Receive Value of Type Double from the User */
        private static double promptUser(string promptEnd)
            Boolean first = true;
            string prompt;
            double doubleValue;           

            // Loop until valid double value is entered
                prompt = "Please enter the" + (first ? " numerical " : " NUMERICAL ") + promptEnd;               
                first = false;
            while (!Double.TryParse(Console.ReadLine(), out doubleValue));
            return doubleValue;