div() in C - Source Code Example

In this source code example, we will see how to use the abs() function in C programming with an example.

div() Function Overview

The abs() function is available in <stdlib.h> returns the absolute value of an integer. In simpler terms, if you provide a negative integer, it gives back the positive version of it. If the integer is already positive or zero, it remains unchanged.

Source Code Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Define some sample numbers
    int num1 = -5, num2 = 13, num3 = 0;

    // Calculate absolute values using abs() function
    int absNum1 = abs(num1);
    int absNum2 = abs(num2);
    int absNum3 = abs(num3);

    printf("Absolute value of %d is %d\n", num1, absNum1);
    printf("Absolute value of %d is %d\n", num2, absNum2);
    printf("Absolute value of %d is %d\n", num3, absNum3);

    return 0;
}

Output

Absolute value of -5 is 5
Absolute value of 13 is 13
Absolute value of 0 is 0

Explanation

1. Three integer variables num1, num2, and num3 are declared with values -5, 13, and 0 respectively.

2. We then calculate the absolute values for each of these numbers using the abs() function.

3. The results are printed out, demonstrating how abs() behaves with negative, positive, and zero values.


Comments