Thread: C program to Calculate Change

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    3

    C program to Calculate Change

    Hello,

    I am very new to programming and am having a hard time with a homework assignment. I am in no way asking anyone to write code for me, just hoping someone can point me in the direction of a Tutorial, Examples etc that I can use to learn from. I have read the required reading for the next lecture and have not found the Mod % function as hinted in the syllabus and pasted below.

    I know how to use the printf function and scanf function to prompt and receive the user input. I am also ok figuring out the amount of change, where I am finding difficulty is with breaking the change down.


    Here is the assignment from the syllabus, again, if someone could point me to some information to read and learn from I would be very much appreciative. We are using Dev-C++ compiler BTW.

    Write a C program to calculate the change converter. Take input from the user for amount
    due and currency note. You are required to give back the balance amount in the least
    denomination (i.e. least amount of currency to be returned). The program must be able to
    calculate in dollars, quarter, dime, nickel and pennies.
    Example:

    Amount Due = $25.52
    Amount Given = $30.00
    Balance Amount = $ 4.48


    Given back in denomination as
    $1 Bill = 4
    Quarters =1
    Dimes = 2
    Nickels = 0
    Pennies = 3
    Hint:
    Use mod function (%)

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You should search (using whatever search mechanism you like) for either "mod" or "modulus" or "% in C" or something similar.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    3
    Quote Originally Posted by tabstop View Post
    You should search (using whatever search mechanism you like) for either "mod" or "modulus" or "% in C" or something similar.
    I have done some googling on the topic but nothing I feel is helping. I found this earlier, see what I put after and let me know if I am o the right track, I believe that is C++ so I will change some of it to make it what I know to be C

    Code:
    #include <iostream>
    
    
    int main()
    {
        int num;
        cin >> num;
        // num % 2 computes the remainder when num is divided by 2
        if ( num % 2 == 0 )
        {
            cout << num << " is even ";
        }
    
        return 0;
    }
    Here is kind of what I am thinking, trustme I am new and at work so I don't have my compiler in front of me or the projects we have done to reference.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        float amtDue = 0;
        float amtGiven = 0;
        float balAmount =0;
    
        float twenty = 20.00
        float ten = 10.00;
        float five = 5.00;
        float one = 1.00;
        float quarter = .25;
        float dime = .10;
        float nickel = .05;
        float penny = .01;
    
        printf ("Enter the Amount Due: ");
        scanf ("%f", &amtDue);
    
        printf ("Enter the Amount Given: ");
        scanf ("%f", &amtGiven);
    
        balAmount = amtDue - amtGiven;
    
        printf ("Change Due: $ %f", balAmount);
        // This is where I really don't know the code but put what my best idea is something like
        
       
        float modTwenty = amtbalance % twenty;
        float modTen = modTwenty % ten;
        // and so on down the line, I can figure out the float or int once I am behind my compiler
        // I am using float because I am using MOD and want the result to be true, then using %d to printf the int so it doesn't say something like 2.3 twenties which is impossible
    
        printf ("Twenties: %d \nTens: %d", modTwenty, modTen);
     
    system ("pause"); 
    return 0;
    }
    Am I getting on the right path???

    i would expect the out put at the end to say something like

    Twenties: 2
    Tens: 1
    and so on...

    Thanks
    Last edited by CaptMorgan; 04-06-2010 at 05:53 PM.

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    I would avoid doing floating point division and expecting to get a remainder.

    Instead, you could just do this:

    1. See how many twenties fit in the sum you need to return. Say that amount is defined by the variable amount. Just do a small loop and subtract the value of 20 at each iteration.
    Code:
    nr_twenties = 0;
    while(amount > 20){
       nr_twenties++;
       amount = amount - 20.0; 
    }
    2. After this do the same to figure out how many 10's fit in the remaining amount. Just one or none, because at this point the amount left is less than 20.

    3. Figure out how many 5's fit in the remaining result.

    etc.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by CaptMorgan View Post
    I have done some googling on the topic but nothing I feel is helping. I found this earlier, see what I put after and let me know if I am o the right track, I believe that is C++ so I will change some of it to make it what I know to be C


    Here is kind of what I am thinking, trustme I am new and at work so I don't have my compiler in front of me or the projects we have done to reference.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        float amtDue = 0;
        float amtGiven = 0;
        float balAmount =0;
    
    
    /* all these variables should be int type. You never give or receive 1.25 ten (for instance) */
        float twenty = 20.00
        float ten = 10.00;
        float five = 5.00;
        float one = 1.00;
        float quarter = .25;
        float dime = .10;
        float nickel = .05;
        float penny = .01;
    
        printf ("Enter the Amount Due: ");
        scanf ("%f", &amtDue);
    
        printf ("Enter the Amount Given: ");
        scanf ("%f", &amtGiven);
    
        balAmount = amtDue - amtGiven;
    
        printf ("Change Due: $ %f", balAmount);
        // This is where I really don't know the code but put what my best idea is something like
        
       
        /* start right off translating all monies into pennies. Why? Because then you have a 
    common base for every bit of arithmetic, and you have no float problem of rounding. 
    Try to print up 12.33 as a float, for instance. */
    
        float modTwenty = amtbalance % twenty;
        float modTen = modTwenty % ten;
        // and so on down the line, I can figure out the float or int once I am behind my compiler
        // I am using float because I am using MOD and want the result to be true, then using %d 
        //to printf the int so it doesn't say something like 2.3 twenties which is impossible
    
        printf ("Twenties: %d \nTens: %d", modTwenty, modTen);
     
    system ("pause"); 
    return 0;
    }
    Am I getting on the right path???

    i would expect the out put at the end to say something like

    Twenties: 2
    Tens: 1
    and so on...

    Thanks
    Yes. You must first multiply all monies by 100 to get everything into pennies. THEN you can start "peeling off" the digits with % and then divide by ten, to get one number place digit, at a time.

    There is a slick arithmetic way of calculating this, but it's not intuitive, really. I prefer the
    Code:
    while(balAmt > 0) {
       if(balAmt > 2000) {
          //code to handle it
       }
       else if(balAmt > 1000) {
         //code to handle that
       }
        //etc.
    }
    type of program for a first time through the "making change" problem.

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I'll add the thing I always add to discussions of the "making change" homework assignment. DON'T USE FLOATS!

    Money is not a floating point number. Money is a fixed precision number. Here's a little demonstration of the problem:
    Code:
    #include <stdio.h>
    
    int main() {
            float i;
            for (i=0.0f; i<20; i+=0.1f) {
                    printf("%f\n",i);
            }
            return 0;
    }
    Here's a little sample of the unexpected output:

    2.500000
    2.600000
    2.700000
    2.799999
    2.899999
    2.999999
    3.099999


    This just compounds. Floats can only accurately represent fractions produced by dividing 1 by 2: 1/2, 1/4/, 1/8, 1/16, 1/32 and so on. Notice 1/10 ("0.1") is not on the list. You may think you can get out of this with rounding, but you probably won't.

    When dealing with change, use an int to represent cents:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
    	int cents = 537;
    	printf("$%d.%02d", cents/100, cents%100);
    
    	return 0;
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    3
    Hello,

    Thanks for the responses. I really am trying to use the mod% function as my teacher indicated in the syllabus. I have been banging my head on this for the last couple hours.

    I have tried a different route after reading this POST and i am already having problems when i tried to figure it out at the change level, imagine the headache I will have once I include the bills.

    This is what I had come up with, and to an extent it was working, with more playing around I am sure I could have gotten it

    Code:
    quarter = change / 25;
        dime = (change - (quarter * 25)) / 10;
        nickel = (change - ((quarter * 25) - (dime * 10))) / 5;
        penny = (change - ((quarter * 25) - (dime * 10) - (nickel * 5))) / 1;
        
        printf ("There are: %d quarters \n There are %d dimes \n There are %d nickels \n and %d pennies", quarter, dime, nickel, penny);
    MK27, once I got to my compiler I quickly saw my values were 2.50000 as you advised.

    I tried to combat this with

    Code:
    balAmount = (amtGiven - amtDue) * 100;
    This seemed to work but I still am unaware of the rest. I am not advanced enough to understand the suggestions provided and they really didn't use the mod% function as we are supposed to.

    At this point I am feeling more lost than earlier

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you aren't sure how mod works, you can do it this way:

    x = 12345
    y = x / 10 (or 1234 )
    z = y * 10 (or 12340)
    x - z = 5

    That's basically how mod works. It just wraps it all up in a single operation.


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Remember that "slick arithmetic method", way that I mentioned before? Well that POST you linked to was going that way.

    I don't advise that, because it's not intuitive, at all. 99% of us think like this while loop, when we give change back on a sale:



    Code:
    /* first, multiply all amounts by 100, to make everything an integer, then */
    
    while(balAmt > 0) {               //while there is an amount due back to the customer
       if(balAmt > 2000) {            //try the largest bill first -- does he get one of those?
          //code to handle it          //if so, subtract $20 (2000 pennies) from the amount 
       }                                 //we still owe.
       else if(balAmt > 1000) {     //and repeat this for the $10 denomination on the next loop
         //code to handle that
       }
        //etc.
    }                             
    //until the
    My advice? Read no more posts on it. Think about the code I've posted here. Isn't that how you actually think when you give back change?

    Item cost $15.82. Customer gave you $20.00.

    amtDue = 2000 - 1582
    amtDue = 418 cents

    Start loop: {

    Do I owe customer >= 2000 ? No too much
    else Do I owe customer >= 1000 ? No too much
    else Do I owe customer >= 500 ? No too much
    else Do I owe customer >=100 ? Yes. { //1st,2nd,3rd & 4th time thru loop
    Give 100 (one dollar)
    Subtract 100 from amtDue
    }
    else Do I owe customer >25 ?
    else Do I owe customer >10 ? { //5th time thru the loop, yes
    give 10 (one dime)
    subtract 10 from amtDue
    }
    else Do I owe customer >5 ? { //6th time thru the loop, yes
    give 5 (one nickel)
    subtract 5 from amtDue
    }
    else Do I owe customer > 1 ? { //7th, 8th, 9th time thru the loop, yes
    give 1 cent to customer
    subtract 1 from amtDue
    }
    }
    END of Loop
    amtDue will equal 0 after 9 loops.

    You have to use logic from greater denominations to lesser, so you don't wind up giving the customer nothing but pennies.

    Now, on to the way your teacher wants you to do this, using % (mod).

    Consider the number line. Since our money system is decimalized (yes, that's a word), it fits beautifully into the base 10 number system:

    These amounts are all in pennies (you've done the money X 100, already)
    Code:
    100's | 10's | 1's, |
    ==================
      4      1     8
    That is amtDue of 418 cents. This time, we work from right to left, and go from smallest denominations, on up.

    Start loop: {

    right most digit = amtDue % 10:
    8 == 418 % 10 //we owe 8 pennies
    if(pennies >= 5)
    give 1 nickel, and subtract 5 from pennies due

    divide 418 by 10, using integer division (standard with integers in C). 418 becomes 41. The 8 remainder is dropped (but we want that, since it's already been handled).
    }
    End of Loop

    Showing 2nd time through the above loop:
    1 == 41 % 10 //now we're up to the 10's place (dimes), and we owe 1 dime

    amtDue = amtDue / 10 (shorthand C is: amtDue /= 10)

    Showing 3rd time through the above loop:
    4 == now we're up to 100's place, so we owe 4 1 dollar bills

    amtDue /= 10

    amtDue is now zero. No more change to make.

    See how % 10 gets the right most digit, and how dividing by 10 truncates it away, digit by digit? It's like you were peeling off the digits, from the right hand side of the amtDue.
    Last edited by Adak; 04-07-2010 at 12:33 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Client-server system with input from separate program
    By robot-ic in forum Networking/Device Communication
    Replies: 3
    Last Post: 01-16-2009, 03:30 PM
  2. Replies: 1
    Last Post: 01-24-2005, 02:07 PM
  3. Change of base program
    By cdonlan in forum C Programming
    Replies: 2
    Last Post: 01-17-2005, 04:51 PM
  4. Need HELP with Program
    By Jeff in forum C Programming
    Replies: 25
    Last Post: 09-23-2004, 08:03 PM