Reputation: 1709
Is there a way to shorten this:
if (a > 0)
printf("%d", a);
else
printf("%d", -a);
I mean, is there a way to write all this inside one printf
with the ?
operator?
Upvotes: 1
Views: 4056
Reputation: 4041
Use the ternary operator.
printf("%d\n",(a>0) ? a:-a);
If the condition is true
, then after the ?
will be executed. Otherwise, after the :
will be executed.
Upvotes: 3
Reputation: 37944
It looks that you want to obtain an absolute value. For int
type you might use abs()
function from <stdlib.h>
header for such purpose:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a;
a = 3;
printf("%d\n", abs(a));
a = -3;
printf("%d\n", abs(a));
return 0;
}
There are also labs()
for llabs()
(C99) for long int
and long long int
types respectively as well as for floating-point types e.g. fabs()
from <math.h>
.
Upvotes: 2
Reputation: 59701
This should work for you:
printf("%d", (a > 0? a: -a));
Input/Output:
5 -> 5
-5 -> 5
A little test program:
#include<stdio.h>
int main() {
int a = -5, b = 5;
printf("%d\n", (a > 0? a: -a));
printf("%d\n", (b > 0? b: -b));
return 0;
}
Upvotes: 6