Advertisement
Guest User

CS50 2024 - Week 1 - Cash

a guest
Feb 9th, 2024
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | Source Code | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3.  
  4. // This problem set is so much more confusing when you're not American
  5. // or British and can't remember what quarters/nickels/dimes/pennies are...
  6.  
  7. // --------------------
  8. // ---- PROTOTYPES ----
  9. // --------------------
  10.  
  11. int get_change(void);
  12. int quarters_calc(int change);
  13. int nickels_calc(int change);
  14. int dimes_calc(int change);
  15. int pennies_calc(int change);
  16.  
  17. // -----------------------
  18. // ---- MAIN FUNCTION ----
  19. // -----------------------
  20.  
  21. int main(void)
  22. {
  23.     int change = get_change();
  24.  
  25.     int quarters = quarters_calc(change);
  26.     change = change - quarters * 25;
  27.  
  28.     int dimes = dimes_calc(change);
  29.     change = change - dimes * 10;
  30.  
  31.     int nickels = nickels_calc(change);
  32.     change = change - nickels * 5;
  33.  
  34.     int pennies = pennies_calc(change);
  35.     change = change - pennies;
  36.  
  37.     int coins = quarters + nickels + dimes + pennies;
  38.  
  39.     printf("%i\n", coins);
  40. }
  41.  
  42. // --------------------------
  43. // ---- CUSTOM FUNCTIONS ----
  44. // --------------------------
  45.  
  46. // Asks the user how much change he needs
  47. int get_change(void)
  48. {
  49.     int change;
  50.     do
  51.     {
  52.         change = get_int("Change owed: ");
  53.     }
  54.     while (change < 0);
  55.     return change;
  56. }
  57.  
  58. // Calculates the number of quarters (25c) needed
  59. int quarters_calc(int change)
  60. {
  61.     int quarters = 0;
  62.     while (change >= 25)
  63.     {
  64.         change = change - 25;
  65.         quarters++;
  66.     }
  67.     return quarters;
  68. }
  69.  
  70. // Calculates the number of dimes (10c) needed
  71. int dimes_calc(int change)
  72. {
  73.     int dimes = 0;
  74.     while (change >= 10)
  75.     {
  76.         change = change - 10;
  77.         dimes++;
  78.     }
  79.     return dimes;
  80. }
  81.  
  82. // Calculates the number of nickels (5c) needed
  83. int nickels_calc(int change)
  84. {
  85.     int nickels = 0;
  86.     while (change >= 5)
  87.     {
  88.         change = change - 5;
  89.         nickels++;
  90.     }
  91.     return nickels;
  92. }
  93.  
  94. // Calculates the number of pennies (1c) needed
  95. int pennies_calc(int change)
  96. {
  97.     int pennies = 0;
  98.     while (change >= 1)
  99.     {
  100.         change = change - 1;
  101.         pennies++;
  102.     }
  103.     return pennies;
  104. }
  105.  
Tags: Cash
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement