C++: modulus


HOME]  Consulting  Design  Maintenance  Project  Testing  Training  Turnkey  Java  C++  SQL  HTML  JavaScript  c# 
© 2002  2016 All Rights Reserved Total Application Works
<html> <head> <title>Example of a link </title> </head> <body> <a href="http://sumtotalz.com/TotalAppsWorks/CPP/CPP_Modulus.html"> Programming Tutorials: modulus </a> </table> </body> </html> 

Source code 
The Modulus.zip file contains the following files:
To run any of the projects:
This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on c++ or programming. In this tutorial, we will briefly discuss variables, as we ease into c++. c++ as a programming language is widespread and can be found on nearly all computers.
What is the modulus operator? The modulo operation finds the remainder of division of one number by another number e.g., 6/5 = 1.
Consider two positive numbers, where a is the dividend and n is the divisor e.g., a/n, a modulo n (abbreviated as a mod n = b), where b is the remainder. For example, the expression "9 mod 8" would evaluate to 1 because 9 divided by 8 results in a remainder of 1,
whereas, "4 mod 2" results in a remainder of 0. Consider the examples in Figure 1 below.

Figure 1: Examples using the modulus function 

How is the modulus operator is useful? It is commonly
used to take a randomly generated number and reduce that number to a random
number on a smaller range. For example, the following figures shows the frequency a number appears
when a die is rolled 100 times.
#include <iostream> int main() { int roll ; const int arraySize = 100; int face, frequency[ arraySize ] = { 0 }; srand( time( 0 ) ); for ( roll = 1; roll <= 100; roll++ ) ++frequency[ 1 + rand() % 6 ]; cout << "Face" << setw( 13 ) << "Frequency" << endl; // ignore element 0 in the frequency array for ( face = 1; face < 7; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl; return 0 ; } 
Output 

Face Frequency 1 15 2 10 3 18 4 13 5 14 6 17 
Figure 2: Frequency of die rolls 
#include <iostream> using namespace std; int main() { int num , num2; do { cout << "Enter an integer dividend" << endl ; cin >> num; cout << "Enter an integer divisor" << endl ; cin >> num2; cout << num << " % " << num2 << " equals " << ( num % num2) << endl; cout << "Enter an 1 to quit" << endl ; cin >> num ; if( num == 1 ) break ; } while (num != 1 ) ; return 0; } 
Figure 3: Example II using the modulus function 

The purpose of this tutorial was to:
HOME]
Consulting
Design
Maintenance
Project
Testing
Training
Turnkey
Java
C++
SQL
HTML
JavaScript
c#
To contact us
© 2002  2016 All Rights Reserved Total Application Works