C++ div()

The div() function is defined in <cstdlib> header file.

Mathematically,

quot * y + rem = x

div() prototype [As of C++ 11 standard]

div_t div(int x, int y);
ldiv_t div(long x, long y);
lldiv_t div(long long x, long long y);

It takes a two arguments x and y, and returns the integral quotient and remainder of the division of x by y.

The quotient quot is the result of the expression x / y. The remainder rem is the result of the expression x % y.


div() Parameters

  • x - the numerator
  • y - the denominator

div() Return value

The div() function returns a structure of type div_t, ldiv_t or lldiv_t. Each of these structure consists of two members: quot and rem. They are defined as follows:

div_t:
struct div_t {
  int quot;
  int rem;
};

ldiv_t:
struct ldiv_t {
  long quot;
  long rem;
};

lldiv_t:
struct lldiv_t {
  long long quot;
  long long rem;
};

Example: C++ div() Function

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {

  div_t result1 = div(51, 6);

  cout << "Quotient of 51/6 = " << result1.quot << endl;
  cout << "Remainder of 51/6 = " << result1.rem << endl;

  ldiv_t result2 = div(19237012L,251L);

  cout << "Quotient of 19237012L/251L = " << result2.quot << endl;
  cout << "Remainder of 19237012L/251L = " << result2.rem << endl;

  return 0;
}

Output

Quotient of 51/6 = 8
Remainder of 51/6 = 3
Quotient of 19237012L/251L = 76641
Remainder of 19237012L/251L = 121