ComputerWeb Design

The Modulus Operator in C++ With Examples

An Overview of Modulus

The remainder of a division of one integer by another is returned by the modulus operator. When two numbers are divided, we get an equation that looks like this:

A/B = Q Remainder R where

The dividend is A.

The divisor is B.

The quotient is Q.

R stands for “remainder.”

When we divide A by B, we are sometimes simply interested in the leftovers. However, there is a modulus operator that may be used in these situations (abbreviated as mod).

If we use the same A, B, Q, and R as before, we get: A mod B = R.

It is expressed as A modulo B equals R, with B referred to as the modulus.

The modulus operator is used to determine whether or not a number is a factor of another number. It can also produce a random number or determine whether a number is even or odd.

Modulus Operator in C++

How would you solve a basic arithmetic problem like above in a computer language like C or C++? The modulus operator (‘ % ‘) is a built-in technique in C and C++ languages that computes the remainder after completing integer division. Consider the following software, which accepts a user-supplied integer and divides it by 3 to get the remainder.

#include <iostream>
using namespace std;
int main()
{
    int num;
    cin >> num;
    return num % 3;
}
Consider the following example, which determines whether the given number is a leap year and returns 1 if it is, else returns 0.
#include <iostream>
using namespace std;
int main()
{
    int nCentury;
    cin >> nCentury;
    if ((nCentury % 4) == 0) {
      return 1;
   }
return 0;
}
You may also use the modulus operator to determine if an integer is odd or even. You can do so by asking for the remainder of a number after it has been divided by two.
#include <iostream>
using namespace std;
int main()
{
    int evenNum;
    cin >> evenNum;
    if (evenNum % 2 == 0 )
    {
        cout << evenNum << " is even ";
    }
    else
    {
        cout << evenNum << " is NOT even ";
    }
    return 0;
}

std::modulus

When T is not given, the C++ standard library offers a specialization of std::modulus, which leaves the parameter types and return values to be derived. The outcome of the mod operation between its two parameters is given by the binary function object class which returns the result of the modulus operation between its two arguments (as returned by operator percent ). The modulus is used in the following C++ code to determine if a number in an array is even or odd.

#include <iostream> // std::cout
#include <functional>   // std::modulus, std::bind2nd
#include <algorithm>    // std::transform
int main () {
  int numbers[]={1,2,3,4,5};
  int remainders[5];
  std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2));
  for (int i=0; i<5; i++)
    std::cout << numbers[i] << " is " << (remainders[i]==0?"even":"odd") << '\n';
  return 0;
}
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd

What are the practical applications of the Modulus Operator?

Knowing how to calculate the remainder of a division (modulus operator) is quite valuable in a variety of scenarios. Consider the following scenario:

Example 1: Find the number of seconds, get the hours, minutes, and seconds.

This is a basic example in which we are assigned a number of seconds and can use the modulo operator to calculate the number of hours, minutes, and seconds and format it in the right time format.

#include <iostream>
using namespace std;
int main ()
{
  int seconds;
  int minutes;
  int hours;
  int numSeconds;
  cout << "Please enter number of seconds: ";
  cin >> numSeconds;
  hours = numSeconds / 3600;
  minutes = (numSeconds / 60) % 60;
  seconds = numSeconds % 60;
  cout << numSeconds << " seconds is: " << hours << " Hours, ";
  cout << minutes << " Minutes and " << seconds << " Seconds ";
  return 0;
}

Example 2: Rotating Through Limited Options (Circular Array)

In some cases, we may only have a limited number of alternatives to choose from. For example, we have three employees, one of whom is required to work the night shift every day, seven days a week. As a result, we can use the modulo operation to travel over an array of days in a loop.

#include <iostream>
using namespace std;
int main ()
{
    // array of days that we want to cycle through
    string weekdays[7] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
    // couunt nummber of days in weekdays array
    int dayCount = sizeof( weekdays ) / sizeof( weekdays[ 0 ] );
    //total number of employees
    int employeeCount = 15;
    //starting day number
    int dayIndex = 0;
    // loop through the employees while rotating through days
    for(int i=0; i < employeeCount; i++ ) {
      // employee number mod option count
      dayIndex = i % dayCount;
      // use dayIndex to find name of the day from weekdays array
      string weekday = weekdays[ dayIndex ];
      cout << "Employee #" << i + 1 << " is scheduled on " << weekday << ". \n";
    }
  return 0;
}

Also Read:

How to Study Well in a Short Amount of Time

C/C++ Operators List

There are many different types of built-in operators in C/C++, and they are divided into three categories such as unary, binary, and ternary operators.

  • Unary Operators
  • Arithmetic Operators
  • Bit-wise Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • Conditional Operators

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button
adana eskort - eskort adana - adana eskort bayan - eskort - mersin eskort