What is div() in C++?
We can use the div() function to calculate the integral quotient and remainder of the division of two numbers.
where,
quotient(x / y) = floor(x / y)remainder(x / y) = x % y
% represents the modulus operator.
Mathematically, the quotient Q and remainder R of the division x/y can be represented as:
Library
To use the div() function, include the following library:
#include <cstdlib>
Declaration
The div() function is declared as:
div_t div(int x, int y);
Or:
ldiv_t div(long x, long y);
Or:
lldiv_t div(long long x, long long y);
x: The numerator of the division.y: The denominator of the division.
Return value
The div() function returns a struct data structure of type div_t, ldiv_t, or lldiv_t that contains the quotient and remainder of the division. The quotient and the remainder can be accessed as shown below:
div_t div1 = div(x, y);
quotient = div1.quot;
remainder = div1.rem;
Note: If denominator
yis0, a floating-point exception is thrown.
Code
Example 1
Consider the code snippet below, which demonstrates the use of the div() function:
#include <cstdlib>#include <iostream>using namespace std;int main() {div_t div1 = div(19, 3);cout << "Quotient(19/3) = " << div1.quot << endl;cout << "Remainder(19/3) = " << div1.rem << endl;return 0;}
Explanation
We use the div() function in line 6 to compute the quotient and remainder of two numbers. The return value of div() is assigned to a div_t type variable that is named div1. The quotient and remainder of the division can be accessed using div1.quot and div1.rem, respectively.
Example 2
Consider the code snippet below, which demonstrates the execution of the div() function when the denominator is 0:
#include <cstdlib>#include <iostream>using namespace std;int main() {div_t div1 = div(19, 0);cout << "Quotient(19/0) = " << div1.quot << endl;cout << "Remainder(19/0) = " << div1.rem << endl;return 0;}
Explanation
A floating-point exception is thrown because the denominator of the division is 0.
Free Resources