C library - div() function



The C stdlib library div() function is used to divide numerator by denominator. It then return the integral quotient and remainder.

For example, pass the numerator 100 and denominator 6 to the div() function in order to obtain the result. Find the quotient by evaluating the 'result.quot' (100/6 = 16) and the remainder by evaluating 'result.rem' (100%6 = 4).

Syntax

Following is the C library syntax of the div() function −

div_t div(int numer, int denom)

Parameters

This function accepts the following parameters −

  • numer − It represents a numerator.

  • denom − It represents a denominator.

Return Value

This function returns the value in a structure defined in <cstdlib> with two members: int 'quot' and int 'rem'.

Example 1

In this example, we create a basic c program to demonstrate the use of div() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int numerator = 100;
   int denominator = 8;
   
   // use div function	
   div_t res = div(numerator, denominator);
   
   printf("Quotient of 100/8 = %d\n", res.quot);
   printf("Remainder of 100/8 = %d\n", res.rem);
   
   return 0;
}

Output

Following is the output −

Quotient of 100/8 = 12
Remainder of 100/8 = 4

Example 2

In the below example, we are passing both numerator and denominator as a negative value to the div() function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int numerator = -100;
	int denominator = -12;
	
	// use div function	
	div_t res = div(numerator, denominator);

	printf("Quotient of 100/8 = %d\n", res.quot);
	printf("Remainder of 100/8 = %d\n", res.rem);
	
	return 0;
}

Output

Following is the output −

Quotient of 100/8 = 8
Remainder of 100/8 = -4

Example 3

Here is the c program to display the Dividend, Divisor, Quotient, and Remainder.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int nums[3] = {7, 10, 35};
   int den[3] = {2, 4, -5};
   div_t res;   
   int i,j; 
   
   printf("Table of result:\n");
   for (i = 0; i < 3; i++){
      for (j = 0; j < 3; j++)
      {
         res = div(nums[i],den[j]);
         printf("Dividend: %4d  Divisor: %4d", nums[i], den[j]);
         printf("  Quotient: %4d  Remainder: %4d\n", res.quot, res.rem);
      }
   }     
}

Output

Following is the output −

Table of result:
Dividend:    7  Divisor:    2  Quotient:    3  Remainder:    1
Dividend:    7  Divisor:    4  Quotient:    1  Remainder:    3
Dividend:    7  Divisor:   -5  Quotient:   -1  Remainder:    2
Dividend:   10  Divisor:    2  Quotient:    5  Remainder:    0
Dividend:   10  Divisor:    4  Quotient:    2  Remainder:    2
Dividend:   10  Divisor:   -5  Quotient:   -2  Remainder:    0
Dividend:   35  Divisor:    2  Quotient:   17  Remainder:    1
Dividend:   35  Divisor:    4  Quotient:    8  Remainder:    3
Dividend:   35  Divisor:   -5  Quotient:   -7  Remainder:    0
Advertisements