Task: Read an integer and print its absolute value without using library functions. If it is negative, multiply by -1
; otherwise leave unchanged.
/*
Program: Absolute Value (no library) — U1
What it does:
- Reads an integer n.
- If n is negative, makes it positive by multiplying by -1.
- Prints the absolute value.
Note:
- Works for typical 32-bit int ranges. Beware of the corner case INT_MIN (-2147483648) on two's-complement systems,
where -INT_MIN cannot be represented as +2147483648 in a 32-bit int. For 1st year, this detail can be ignored.
*/
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input. Please enter a valid integer.\n");
return 0;
}
/* Core logic: if negative, flip the sign */
if (n < 0) {
n = -n;
}
printf("Absolute value = %d\n", n);
/* Examples:
Input: 42 -> Absolute value = 42
Input: -17 -> Absolute value = 17
Input: 0 -> Absolute value = 0
*/
return 0;
}