div() Function
The div()
function in C performs integer division by returning both the quotient and the remainder as a single structure. This allows you to retrieve the results of a division operation without needing to compute the remainder separately.
Syntax of div()
div_t div(int numer, int denom);
Parameters
Parameter | Description |
---|---|
numer | Value to be divided (numerator). |
denom | Value by which the numerator is divided (denominator). Behavior is undefined if this value is zero. |
The function returns its result as a structure of type div_t
, which contains two members: one for the quotient and one for the remainder. This structure facilitates the retrieval of both division outcomes with a single function call.
Return Value
The function returns a div_t
structure containing the integral quotient in the quot
member and the remainder in the rem
member.
Examples for div()
Example 1: Basic Integral Division with Positive Numbers
This example demonstrates how to use div()
to perform division on two positive integers and obtain both the quotient and remainder.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int numerator = 20;
int denominator = 3;
div_t result = div(numerator, denominator);
printf("Quotient: %d\n", result.quot);
printf("Remainder: %d\n", result.rem);
return 0;
}
Explanation:
- The program defines two positive integers: one as the numerator and the other as the denominator.
- The
div()
function is called with these values, returning a structure containing the quotient and remainder. - The program prints the quotient and remainder to the console.
Output:
Quotient: 6
Remainder: 2
Example 2: Division with a Negative Numerator
This example illustrates how div()
handles a situation where the numerator is negative, affecting both the quotient and the remainder according to the rules of integer division.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int numerator = -20;
int denominator = 3;
div_t result = div(numerator, denominator);
printf("Quotient: %d\n", result.quot);
printf("Remainder: %d\n", result.rem);
return 0;
}
Explanation:
- The program initializes a negative numerator with
-20
and a positive denominator with3
. - The
div()
function computes the quotient and remainder according to integer division rules for negative values. - The results are printed, showing how the negative numerator affects the outcome, both quotient and remainder.
Output:
Quotient: -6
Remainder: -2