Thread: Need help with C program

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    16

    Need help with C program

    I am trying to write a C program to calculate change due. How would I go about doing this? It needs to print the amount of change due for each coin/dollar.

    For Example, lets say someone is due back $45.35, I need it to calculate and print how many 20's, 10's, 5's, 1's, quarters, dimes, nickels and pennies must be handed out in order to equal that amount.

    I am lost!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    First, you break it down into steps. Then you convert that into code. Logicly, in your mind, break down how you give change to someone. You do know how to give change, right? Start with the largest amount, which is smaller or equal to the amount of change, and subtract that. Keep subtracting it until the remainder is smaller than that money size. Then move down to the next smaller size. Repeat until you have given all of the change you need.

    Now it's your turn.

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

  3. #3
    Registered User
    Join Date
    Nov 2004
    Posts
    16
    1) I enter price of item
    2) I enter amount paid
    3) Subtract amount paid minus the price
    4) print this number as change due,

    then I step by step need to ask it to calculate the number of each bill due. This is where I get confused on how to do this and put it into C...

  4. #4
    Ah, that's a good start.

    Converting ideas to the C language is not difficult. It is almost like taking your ideas and talking them through to the compiler. For example.

    1) I enter price of item
    » This tells us we need to either write a function or use a standard function to get input from the user. The best way to find out how to do this is some searching. To make this easier, lets just say we happened upon a site: cplusplus.com reference. This is a good site that explains most, if not all, of the standard library functions within the C language. We spot out stdio.h, string.h, and stdlib.h first. We know string.h has to do with strings, and stdlib with the standard library, while stdio is for I/O or Input and Output. Exactly what we need!

    We scroll down for a bit and happen upon scanf(). What does this function do? It reads formatted data from stdin. Also what we need. stdin is the input stream, while stdout is the output stream.

    Of course you can learn more about scanf() by clicking here.

    2) I enter amount paid
    » We do the same above but again with another variable. One for amount, and one for price.

    3) Subtract amount paid minus the price
    » Mathematics in C isn't any harder than paper. Just do: difference = paid - price. Quite simple in terms.

    4) print this number as change due
    » We we know about scanf() that takes input, but what about a function that prints output. If we go back to the cplusplus.com reference page we can look 8 functions up from where you found scanf(). What do we see? printf(). What does printf() do? It prints formatted data to stdout. Exactly. It works almost identical to scanf() though we print out variables that already exist. Here is more info about printf().

    I hope this helps. If you have further questions, please feel free to ask.

    Note: Each of the links of printf() and scanf() have full examples at the bottom of each page.

    I hope this helps you get started. The ideas you have in mind for your project will take more than the first 4 steps, but its a start!


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    1) Loop through your bills starting at the largest
    2) While the value of that bill plus the amount of change you've already handed out is less than the total change due, give another bill.
    If you understand what you're doing, you're not learning anything.

  6. #6
    Registered User
    Join Date
    Nov 2004
    Posts
    16
    I think I get it, but do you mind giving me a quick example. Say, change due is $43.00. Show me, with the loop, I assume a while statement, I would calculate and have it print the number of 20's to hand out....

  7. #7
    > do you mind giving me a quick example
    » Not at all. Just for examples sake lets look at the following.

    The while loop
    The while loop has a syntax of the following:
    Code:
    while (expression) {
    	statement
    }
    This should make sense. As long as the expression is true, the statement executes.

    So lets take for instance 43 dollars. If we wanted to sucessfully find how many tens are in forty-three dollars all we would have to do is run a while loop in statement like the following:
    Code:
    As long as money is greater than 10
    Subtract 10
    Increment tens counter
    If this makes sense, so should this:
    Code:
    int tens = 0, money = 43;
    
    while (money > 10) {
    	money -= 10;
    	tens++;
    }
    That is just an example of how it could work. Everytime the while loop executes, money is subtracted by 10 and our integer called tens is incremented. The answer should be '4 tens'. After a while the loop does run out of 10's to subtract. Though of course we haven't printed any output so we would never know.

    If you have further questions, please feel free to ask.


    - Stack Overflow
    Last edited by Stack Overflow; 11-11-2004 at 07:28 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  8. #8
    Registered User
    Join Date
    Nov 2004
    Posts
    16
    Ok, now lets say I dont want a person to enter a value for cost or payment, etc., but that the info is already stored in a file that I want the program to open, scan and then calculate the change due, based on the information in that file....

  9. #9
    Alright,

    You haven't gone off my page yet

    Lets go back to the cplusplus reference page. We are familar with scanf() and printf(), though there is a new one: fscanf()

    Why is it called fscanf()? Because it reads formatted data from a stream. File Scan Format - fscanf() [or that is my analogy]

    How does fscanf() work? Well, that link should show you everything you need to know.

    fscanf() does need an open stream of a file. Though we haven't opened a file yet. How do we? We use fopen() - File Open [simple, eh?]

    fopen() works like a charm. You open a file with your filename and you can read it into memory, or better yet just open it and start scanning away with fscanf(). If you look near the bottom of fscanf()'s page you will see fopen() and fclose() being used.

    This works like the following:
    Code:
    Open the file
    Scan inside the file
    Close the file

    Hope this helps,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define STAGE_LEFT EXIT_FAILURE
    #define ENCORE EXIT_SUCCESS
    #define TOO_SHORT NULL
    #define toilet stdout
    #define BLING 1
    #define EMPTY_WALLET 0
    
    double jinglie[] = {
      100.00, 50.00, 20.00, 10.00, 5.00, 1.00, .50, .25, .10, .05, .01
    };
    
    int main ( void )
    {
      char thingie[BUFSIZ];
      double all_zat, da_dough, leftovas;
    
      printf ( "Price: " );
      fflush ( toilet );
      if ( fgets ( thingie, sizeof thingie, stdin ) == TOO_SHORT
        || sscanf ( thingie, "%lf", &all_zat ) != BLING )
      {
        exit ( STAGE_LEFT );
      }
    
      printf ( "Amount: " );
      fflush ( toilet );
      if ( fgets ( thingie, sizeof thingie, stdin ) == TOO_SHORT
        || sscanf ( thingie, "%lf", &da_dough ) != BLING )
      {
        exit ( STAGE_LEFT );
      }
    
      leftovas = da_dough - all_zat;
    
      printf ( "Change Due:\n" );
      if ( leftovas >= EMPTY_WALLET ) {
        int stuff = 0;
    
        while ( stuff < sizeof jinglie / sizeof *jinglie ) {
          if ( leftovas >= jinglie[stuff] ) {
            printf ( "%.2f\n", jinglie[stuff] );
            leftovas -= jinglie[stuff];
          }
          else
            ++stuff;
        }
      }
      else
        printf ( "You still owe %.2f\n", fabs ( leftovas ) );
    
      return ENCORE;
    }
    Oh, I kill me.
    My best code is written with the delete key.

  11. #11
    Ah Prelude,

    All my efforts for nothing! Just kidding.

    I like the code personally, though it may confuse a beginner programmer.

    All in all, gain help and gain trust; as they say it.


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  12. #12
    UCF Mystic_Skies's Avatar
    Join Date
    Oct 2004
    Posts
    33
    Quote Originally Posted by Prelude
    Oh, I kill me.
    I'm also a beginner but I must say that seeing a program with that kinda personality is really cool
    Never a dull moment around here...lol!

  13. #13
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Quote Originally Posted by Prelude
    Code:
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define STAGE_LEFT EXIT_FAILURE
    #define ENCORE EXIT_SUCCESS
    #define TOO_SHORT NULL
    #define toilet stdout
    #define BLING 1
    #define EMPTY_WALLET 0
    
    double jinglie[] = {
      100.00, 50.00, 20.00, 10.00, 5.00, 1.00, .50, .25, .10, .05, .01
    };
    
    int main ( void )
    {
      char thingie[BUFSIZ];
      double all_zat, da_dough, leftovas;
    
      printf ( "Price: " );
      fflush ( toilet );
      if ( fgets ( thingie, sizeof thingie, stdin ) == TOO_SHORT
        || sscanf ( thingie, "%lf", &all_zat ) != BLING )
      {
        exit ( STAGE_LEFT );
      }
    
      printf ( "Amount: " );
      fflush ( toilet );
      if ( fgets ( thingie, sizeof thingie, stdin ) == TOO_SHORT
        || sscanf ( thingie, "%lf", &da_dough ) != BLING )
      {
        exit ( STAGE_LEFT );
      }
    
      leftovas = da_dough - all_zat;
    
      printf ( "Change Due:\n" );
      if ( leftovas >= EMPTY_WALLET ) {
        int stuff = 0;
    
        while ( stuff < sizeof jinglie / sizeof *jinglie ) {
          if ( leftovas >= jinglie[stuff] ) {
            printf ( "%.2f\n", jinglie[stuff] );
            leftovas -= jinglie[stuff];
          }
          else
            ++stuff;
        }
      }
      else
        printf ( "You still owe %.2f\n", fabs ( leftovas ) );
    
      return ENCORE;
    }
    Oh, I kill me.
    really girl. you just all dat and a big bag 'O chips wit da Dips!!! LOL. seriously, your a goddess. I can't wait till I'm where you are. Kudos.
    flawless!
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  14. #14
    Registered User
    Join Date
    Nov 2004
    Posts
    16
    Just to double check, before I insert it, you said the following code
    fscanf(transactions, "%f\n", &cost);
    printf ("The cost is %g\n", cost);
    fscanf(transactions, "%f\n", &payment);
    printf("The customer's payment was %g\n", payment);
    change = cost - payment;
    printf("The change due is %g\n", change);
    was fine to use?

  15. #15
    Yes, that code is fine.

    fscanf(transactions, "%f\n", &cost);
    > Gets the cost from the file

    printf ("The cost is %g\n", cost);
    > Prints the cost that we got from file

    fscanf(transactions, "%f\n", &payment);
    > Gets the payment from file

    printf("The customer's payment was %g\n", payment);
    > Prints the payment we got from file

    change = cost - payment;
    > Gets the difference between the two

    printf("The change due is %g\n", change);
    > Prints that difference we just calculated.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 01:38 PM
  2. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  3. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM