In: Computer Science
Code in C# please.
Write a program that will use the greedy algorithm.
This program will ask a user to enter the cost of an item.
This program will ask the user to enter the amount the user is paying.
This program will return the change after subtracting the item cost by the amount paid.
Using the greedy algorithm, the code should check for the type of bill.
Example:
Cost of item is $15.50 User pays a $20 bill
$20 - $15.50 = $4.50
Greedy algorithm will then return the user change in bills by checking every bill starting from $20
$20 <= $4.50? no skip
$10 <= $4.50? no skip
$5 <= $4.50? no skip
$1 <= $4.50? yes store $1 and subtract from total
$1 <= $3.50? yes store $1 and subtract from total. Etc
Final output should be User will get 4 dollar bills and 2 quarters.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void
Main(string[] args)
{
float cost,pay;
int [] Array={0,0,0,0,0};
float [] A={20,10,5,1,0.25F};
int size = A.Length;
Console.WriteLine("Enter cost of an item: ");
cost = float.Parse(Console.ReadLine());
Console.WriteLine("\nEnter amount the user is paying: ");
pay = float.Parse(Console.ReadLine());
float remain=pay-cost;
for(int i=0;i<size;i++)
{
if(remain>=A[i])
{
int temp=(int)(remain/A[i]);
remain-=temp*A[i];
Array[i]=temp;
}
}
int doller = 0;
for(int i=0;i<size;i++)
{
Console.WriteLine(Array[i] + " of " + A[i]);
doller += (int)Array[i] * (int)A[i];
}
Console.WriteLine("\ntotal=" + doller + " doller And " + Array[size
- 1] + " quarters");
Console.ReadKey();
}
}
}
//sample output