div() function in C++

This tutorial illustrates the working of the div() function in C++. We can use this function to find the quotient and remainder of a division. The div() function is defined in the cstdlib header file of C++. We will discuss more on this function here.

As the name suggests we use this function in our C++ program in division operation between two parameters. The syntax for this function is as follows:

div_t div(int a, int b);
ldiv_t div(int a, int b);
lldiv_t div(int a, int b);

Here a and b are the numerator and denominator respectively.

The return types for div() function are div_t, ldiv_t, and lldiv_t. These are structures and are defined as given below.


struct div_t{
int quot;
int rem;


struct ldiv_t{ 
long quot;
long rem; 


struct lldiv_t{ 
long long quot; 
long long rem; 

Here, quot is the quotient and rem is the remainder.

If the input parameters in div() function are a and b, then quot = a/b and rem = a%b. We can access these in the same way as we access an element of a structure in C++.

Here is the example program that illustrates the working of div() function.

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

int main()
  div_t out = div(6,4);
  cout << "quotient of 6/4 = " << out.quot << ".\n";
  cout << "remainder of 6/4 = " << out.rem << ".\n";
  return 0;

And the output of the program is:

quotient of 6/4 = 1.
remainder of 6/4 = 2.

Similarly, we can use the div() function for long and long long as well.

Thank you.

Also, read: Print only digits from a string in C++

Leave a Reply

Your email address will not be published. Required fields are marked *