Money Change Program in Java Example

Java Program:

package in.javadomain;

import java.util.ArrayList;
import java.util.ListIterator;

public class MoneyChange {

	public static void main(String[] args) {
		int input = 213;
		int[] money = { 1, 2, 5, 10, 20, 50, 100, 500, 1000 };
		ArrayList<Integer> moneyChange = new ArrayList<Integer>();
		for (int i = money.length - 1; i >= 0; i--) {
			if (input > money[i] || input == money[i]) {
				input = input - money[i];
				moneyChange.add(money[i]);
				System.out.println("You Need to Take Rs.:" + money[i]);
				i = money.length - 1;
			}
		}
		ListIterator li = moneyChange.listIterator(moneyChange.size());
		int changes = 0;
		while (li.hasPrevious()) {
			int temp = (int) li.previous();
			if (temp < input) {
				changes = changes + temp;
			}
		}
	}
}

Output:

You Need to Take Rs.:100
You Need to Take Rs.:100
You Need to Take Rs.:10
You Need to Take Rs.:2
You Need to Take Rs.:1

Recommeded Books:

402 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *