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()

</>
Copy
div_t div(int numer, int denom);

Parameters

ParameterDescription
numerValue to be divided (numerator).
denomValue 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

</>
Copy
#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:

  1. The program defines two positive integers: one as the numerator and the other as the denominator.
  2. The div() function is called with these values, returning a structure containing the quotient and remainder.
  3. 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

</>
Copy
#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:

  1. The program initializes a negative numerator with -20 and a positive denominator with 3.
  2. The div() function computes the quotient and remainder according to integer division rules for negative values.
  3. The results are printed, showing how the negative numerator affects the outcome, both quotient and remainder.

Output:

Quotient: -6
Remainder: -2