Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

Demo Division and Modulus

 Sample program:
(TASK:  Write a program that will group horses into available pastures.  Start by putting an equal number of horses in each pasture.  Indicate how many horses will not be placed in a pasture by this process.  There are always more horses than pastures for this problem.)

#include <iostream.h>
int main(void)
{
     int horses, pastures, horsesInEachPasture;
     int leftOver;                     
    
     cout<<"How many horses are on the farm? ";
     cin>>horses;
     cout<<"How many pastures are available on the farm? ";
     cin>>pastures;

     //compute the number of horses per pasture
     horsesInEachPasture=horses/pastures;    //integer division
     cout<<"\nThere will be "<<horsesInEachPasture<<" horses per pasture.\n";

     //compute the number of left over horses using modulus
     leftOver = horses%pastures;
     cout<<"There will be "<<leftOver<<" horses without a pasture in this process.\n";

     return 0;
}

 

 

Screen Display:

How many horses are on the farm? 10
How many pastures are available on the farm? 3

There will be 3 horses per pasture.
There will be 1 horses without a pasture in this process.
 

 

Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use