Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone please throughly explain to me how the modulo operator (%) works in

ID: 3573590 • Letter: C

Question

Can someone please throughly explain to me how the modulo operator (%) works in this program specifically to get data?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

// Declare variables
double amtdue, amtpaid, difference;
int change, dollars20, dollars10, dollars5, dollars1;
int quarter, nickel, dime, penny;

int main()
{
   // Input
   cout << "Total Amount Due: $";
   cin >> amtdue; cout << endl;
   cout << "Total Amount Paid: $";
   cin >> amtpaid; cout << endl;

   if (amtpaid > amtdue)
   {
       // The amount difference calculate new variables.
       difference = amtpaid - amtdue;
       difference = difference + 0.00001;
       cout << fixed << setprecision(2) << "Total Change Due: $" << difference << endl << endl;
       difference = difference * 100;
       change = (int)(difference);

       //calculation of money that is due
       dollars20 = change / 2000;
       change = change % 2000;
       dollars10 = change / 1000;
       change = change % 1000;
       dollars5 = change / 500;
       change = change % 500;
       dollars1 = change / 100;
       change = change % 100;
       quarter = change / 25;
       change = change % 25;
       dime = change / 10;
       change = change % 10;
       nickel = change / 5;
       change = change % 5;
       penny = change / 1;
       change = change % 1;
  
       // Output
       cout << "Number of twenty dollar bills due: " << dollars20 << endl;
       cout << "Number of ten dollar bills due: " << dollars10 << endl;
       cout << "Number of five dollar bills due: " << dollars5 << endl;
       cout << "Number of one dollar bills due: " << dollars1 << endl;
       cout << "Number of quarters due: " << quarter << endl;
       cout << "Number of dimes due: " << dime << endl;
       cout << "Number of nickels due: " << nickel << endl;
       cout << "Number of pennies due: " << penny << endl;
   }
   else {
       cout << "No change is due." << endl;
   }
   cin.ignore(100);
   return 0;
}

Explanation / Answer

The modulo operator works by returning the remainder obtained when a quotient is divided by a divisor. In your situation, we're looking at change (in cents). Dividing this change by 20$ (=2000 cents), we get the number of 20$ notes to be given out. Now we have left the remainder, which we obtain by the modulo operator. Then we can use a similar approach to calculate the number of $10 notes to be given out, by dividing by 1000. The remainder is calculated, again by modulo. Rinse and repeat.