C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Decision Making Programs in C

Find absolute value of a number

Introduction

The absolute value of a number is its distance from zero, regardless of its sign:

  • Absolute value of 5 is 5.
  • Absolute value of -5 is also 5.

We can use if-else conditions or the abs() function from <stdlib.h> to calculate it.

 

C Program: Find Absolute Value (Using if-else)

Method 1:

C

#include <stdio.h>

 

int main() {

    int num, absolute;

 

    // Input number

    printf("Enter a number: ");

    scanf("%d", &num);

 

    // Check and find absolute value

    if (num < 0) {

        absolute = -num;

    } else {

        absolute = num;

    }

 

    // Display result

    printf("Absolute value of %d is %d\n", num, absolute);

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a number: -15
Absolute value of -15 is 15

Enter a number: 23
Absolute value of 23 is 23
 

Explanation

  1. User enters a number.
  2. If the number is negative, we multiply by -1 to make it positive.
  3. If it’s already positive, we keep it as it is.
  4. The result is displayed.

 

Method 2: Using Built-in Function

You can also use the abs() function from <stdlib.h > :

C

#include <stdio.h>

#include <stdlib.h>  // for abs()

 

int main() {

    int num;

 

    printf("Enter a number: ");

    scanf("%d", &num);

 

    printf("Absolute value of %d is %d\n", num, abs(num));

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a number: -15
Absolute value of -15 is 15

Enter a number: 23
Absolute value of 23 is 23