A friend and I at IT school tasked ourselves with writing something just for the hell of it. Trying to simulate in a very basic way something that you may want to do in the real world. We thought of the following problem that we could solve ourselves.
X, Y and X INC is in need of a program. They wish to promote the sales of their products in bigger quantity. They wish to give the following discounts to promote better sales.
- If 1 to a 100 of a certain item is sold the company wishes to grant a 10 percent discount.
- If the amount of the product sold is between 101 and 200 the company wishes to grant a 12 percent discount.
- If the amount of the product sold is between 201 and 500 the company wishes to grant a 15 percent discount
- If the amount of product sold is greater than 500 the discount should be 20 percent.
The program should take a price input and a quantity input and should give a total with the applicable discount to the end user without divulging the percentage of the discount.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscountApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the quanitity of the product bought.");
var x = Console.ReadLine();
int x1 = int.Parse(x);
Console.WriteLine("Please enter the price of the product bought.");
var y = Console.ReadLine();
double y1 = double.Parse(y);
double discount = 0;
double outValue = 0;
if (x1 <= 100)
{
discount = 0.1;
outValue = returnTotal(discount, y1, x1);
Console.WriteLine("The total with the discount is R{0}",outValue);
}
else if (x1 > 100 && x1 <= 200)
{
discount = 0.12;
outValue = returnTotal(discount, y1, x1);
Console.WriteLine("The total with the discount is R{0}",outValue);
}
else if (x1 > 200 && x1 <= 500)
{
discount = 0.15;
outValue = returnTotal(discount, y1, x1);
Console.WriteLine("The total with the discount is R{0}",outValue);
}
else
{
discount = 0.2;
outValue = returnTotal(discount, y1, x1);
Console.WriteLine("The total with the discount is R{0}",outValue);
}
}
public static double returnTotal(double discount, double price, int quantity)
{
double Total = (price * quantity);
double discountTotal = Total - (Total * discount);
return discountTotal;
}
}
}
I'm not sure if a switch statement would be better. I'm not entirely sure how you would do multiple conditions in the switch statement.

int.Parse/double.Parsewill blow up in your face if the user enters something that isn't a number - you need to wrap those in atry catchstatement to handle this possibility. \$\endgroup\$outValue = ...; Console.WriteLine(...);part can easily be put after the if/else blocks. And a helper method that returns the discount percentage for a given quantity would also help to make the code more readable. Also, as Joe already mentioned,int.Parseand its cousins will throw exceptions on invalid input. Try using theTryParsevariants instead. \$\endgroup\$