C++ div()

The div() function in C++ computes the integral quotient and remainder of the division of two numbers.

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: Represents the numerator.
  • y: Represents 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: How div() function works in C++?

#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;
}

When you run the program, the output will be:

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