A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
div takes an integer numerator and denominator and returns a div_t struct containing both the quotient and the remainder. On most hardware, the division instruction produces both results simultaneously. If you write x / y and x % y separately, the compiler might optimize them into one instruction, or it might not. div guarantees one operation. For long and long long, use ldiv and lldiv.
#include <stdio.h>#include <stdlib.h>int main(void) {div_t result = div(17, 5);printf("17 / 5 = %d remainder %d\n", result.quot, result.rem);ldiv_t lresult = ldiv(1000000007L, 31L);printf("1000000007 / 31 = %ld remainder %ld\n", lresult.quot, lresult.rem);div_t neg = div(-17, 5);printf("-17 / 5 = %d remainder %d\n", neg.quot, neg.rem);return 0;}
The quotient truncates toward zero, matching the / operator. The remainder takes the sign of the dividend, matching the % operator. The invariant is: numerator = quot * denominator + rem. This holds for all inputs except division by zero, which is undefined behavior. div does not check for zero. Neither does the hardware.
div is a micro-optimization that also improves readability when you need both results. Instead of computing the division twice, you compute it once and destructure the result. Next: modf, which splits a floating-point number into integer and fractional parts.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.