Exercises Java with Examples-
Practice Exercises Java 4,5 5 302940

Give change - Practice Exercises Java


Lesson 2:

Flow Control


Exercise 2.34:

Give change


Objetive:

Create a Java program to return the change of a purchase, using coins (or bills) as large as possible. Assume we have an unlimited amount of coins (or bills) of 100, 50, 20, 10, 5, 2 and 1, and there are no decimal places. Thus, the execution could be something like this:

Price? 44
Paid? 100
Your change is 56: 50 5 1
Price? 1
Paid? 100
Your change is 99: 50 20 20 5 2 2


Source Code:


import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		int price, paid, change;

		System.out.print("Price? ");
		price = Integer.parseInt(new Scanner(System.in).nextLine());
		System.out.print("Paid? ");
		paid = Integer.parseInt(new Scanner(System.in).nextLine());

		change = paid - price;
		System.out.printf("Your change is %1$s: ", change);
		while (change > 0)
		{
			if (change >= 50)
			{
				System.out.print("50 ");
				change -= 50;
			}
			else
			{
				if (change >= 20)
				{
					System.out.print("20 ");
					change -= 20;
				}
				else
				{
					if (change >= 10)
					{
						System.out.print("10 ");
						change -= 10;
					}
					else
					{
						if (change >= 5)
						{
							System.out.print("5 ");
							change -= 5;
						}
						else
						{
							if (change >= 2)
							{
								System.out.print("2 ");
								change -= 2;
							}
							else
							{
								System.out.print("1 ");
								change -= 1;
							}
						}
					}
				}
			}
		}
		System.out.println();
	}
}
Exercisey 2.34

Share Now:


Google Ads





Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.