C Program to Find Absolute Value of a Number
To find the absolute value in C, use the code:
if (num < 0) num = -num; which changes negative numbers to positive, leaving positive numbers unchanged.Examples
Input-5
OutputAbsolute value of -5 is 5
Input10
OutputAbsolute value of 10 is 10
Input0
OutputAbsolute value of 0 is 0
How to Think About It
To find the absolute value, check if the number is less than zero. If yes, multiply it by -1 to make it positive. If not, keep it as is because it's already positive or zero.
Algorithm
1
Get the input number from the user2
Check if the number is less than zero3
If yes, multiply the number by -1 to make it positive4
Print the resulting number as the absolute valueCode
c
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (num < 0) { num = -num; } printf("Absolute value of the number is %d\n", num); return 0; }
Output
Enter an integer: -7
Absolute value of the number is 7
Dry Run
Let's trace the input -7 through the code
1
Input
User enters -7, so num = -7
2
Check if num < 0
Since -7 < 0 is true, enter the if block
3
Make num positive
num = -(-7) = 7
4
Print result
Print 'Absolute value of the number is 7'
| Step | num | Condition (num < 0) | Action |
|---|---|---|---|
| 1 | -7 | True | num = -num => 7 |
| 2 | 7 | False | Print 7 |
Why This Works
Step 1: Check if number is negative
The code uses if (num < 0) to find if the number is less than zero.
Step 2: Convert negative to positive
If the number is negative, multiplying by -1 makes it positive.
Step 3: Print absolute value
The final value of num is printed as the absolute value.
Alternative Approaches
Using ternary operator
c
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); num = (num < 0) ? -num : num; printf("Absolute value of the number is %d\n", num); return 0; }
This method is shorter and uses a single line to assign the absolute value.
Using built-in function abs()
c
#include <stdio.h> #include <stdlib.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); printf("Absolute value of the number is %d\n", abs(num)); return 0; }
This uses the standard library function <code>abs()</code> which is simple and reliable.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a constant number of operations regardless of input size, so it runs in constant time.
Space Complexity
Only a fixed amount of memory is used for variables, so space complexity is constant.
Which Approach is Fastest?
All approaches run in constant time; using abs() is simplest and less error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else check | O(1) | O(1) | Understanding logic |
| Ternary operator | O(1) | O(1) | Concise code |
| Built-in abs() | O(1) | O(1) | Simplicity and reliability |
Use the built-in
abs() function for cleaner code when available.Forgetting to handle negative numbers and returning the original value without change.