## Introduction to Modulus

The modulus operator returns the remainder of a division of one number by another. When we divide two integer numbers we will have an equation that looks like the following:

A/B = Q Remainder R where

A is the dividend

B is the divisor

Q is the quotient

R is the remainder

Sometimes, we are only interested in what the remainder is when we divide A by B. For these cases there is an operator called modulo operator (abbreviated as mod).

Using the same A, B, Q, and R as above, we would have: A mod B = R.

We would say this as A modulo B is equal to R where B is referred to as the modulus.

There are multiple uses of modulus operator such as telling if a number is a factor of another number or not. It can also be used to generate a random number or finding an even or odd number as well.

You can also watch detailed video on C++ Modulus Operator below.

The modulus operator % can only be used with integer numbers and always have integer answer. Below is the graphics showing different sets of numbers.

## C++ Modulus Operator

Taking a simple arithmetic problem as shown above, how would you compute this in a programming language such as C or C++? The C and C++ language provides a built-in mechanism, the modulus operator (‘%’), that computes the remainder that results from performing integer division. Consider the following program which takes a number from user and calculates the remainder of the number with divided by 3.

#include <iostream> using namespace std; int main() { int num; cin >> num; return num % 3; }

Take another example below which calculates whether the input number is leap year and returns 1 otherwise return 0.

#include <iostream> using namespace std; int main() { int nCentury; cin >> nCentury; if ((nCentury % 4) == 0) { return 1; } return 0; }

You may also find if a number or odd or even by using modulus operator. You can do this by asking for the remainder of the number when divided by 2.

#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

The C++ standard library provides a specialization of std::modulus when T is not specified, which leaves the parameter types and return type to be deduced. Binary function object class whose call returns the result of the modulus operation between its two arguments (as returned by operator %). For example, the following C++ code find whether the number in an array is even or odd by using the modulus.

#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 real life uses of Modulus Operator?

Knowing the remainder of a division (modulus operator) is immensely useful in lots of real life situations. For example:

#### Example 1: Find Hours, Minutes and seconds from number of seconds

This is simple situation where we are given number of seconds and we can use modulo operator to find number hours, minutes and second and format it in proper time shape.

#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 certain situations, we might have limited number of options to go through. For example, we have three employees and one of them has to perform night shift daily, seven days of the week. So, we can use modulo operation to walk through array of days in a repeating 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; }

## List of C/C++ Operators

C/C++ has many built-in operator types and they are classified as follows and categorized into three broad categories i.e. Unary, Binary and Ternary operators.:

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

### Here's Must-Read List of C programming books for beginners

#### C Programming Language, 2nd Edition

With over 600 5-star reviews on Amazon, readers agree that C Programming Language, 2nd Edition by Brian Kernighan and Dennis Ritchie is the best C Programming book for Beginners. The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures.

#### 21st Century C: C Tips from the New School

Throw out your old ideas about C and get to know a programming language that’s substantially outgrown its origins. With this revised edition of 21st Century C, you’ll discover up-to-date techniques missing from other C tutorials, whether you’re new to the language or just getting reacquainted.

#### C Programming Absolute Beginner's Guide

Greg Perry is the author of over 75 computer books and known for bringing programming topics down to the beginner’s level. His book C Programming Absolute Beginner's Guide, is today’s best beginner’s guide to writing C programs–and to learning skills to use with practically any language. Its simple, practical instructions will help you start creating useful, reliable C code, from games to mobile apps. Plus, it’s fully updated for the new C11 standard and today’s free, open source tools!

#### C Programming: A Modern Approach, 2nd Edition

KN King tackles on some C standard library specifics header by header in his C Programming: A Modern Approach book. The second edition maintains all the book's popular features and brings it up to date with coverage of the C99 standard. The new edition also adds a significant number of exercises and longer programming projects, and includes extensive revisions and updates.

#### Programming Arduino: Getting Started with Sketches

Simon Monk, a Ph.D. in software engineering, writes this great little book for learning to program the arduino using C language. This bestselling guide explains how to write well-crafted sketches using Arduino’s modified C language. You will learn how to configure hardware and software, develop your own sketches, work with built-in and custom Arduino libraries, and explore the Internet of Things—all with no prior programming experience required!