# Thread: How can i convert negative number to positive number ?

1. ## How can i convert negative number to positive number ?

How can i make in such a way that the negative is ignored before adding up the number ??

Eg: I want the following the code to print out 13 instead of -1.

Code:
```
double hello[]={-1,2,4,-6};

for(i=0; i<=3; i++)
{
xxx = xxx + hello[i];
}

printf("%f",xxx);```

2. Code:
```double hello[]={-1,2,4,-6};

for(i=0; i<=3; i++)
{
if(hello[i] < 0)
xxx -= hello[i];        /*  ex: x = x - (-1) */
else
xxx += hello[i];       /* ex: x = x + 2 */
}

printf("%f",xxx);```

3. You can use fabs from <math.h>.
Code:
```#include <stdio.h>
#include <math.h>

int main(void)
{
double hello[]={-1,2,4,-6};
double xxx = 0;
int i;

for(i=0; i<=3; i++)
{
xxx = xxx + fabs(hello[i]);
}

printf("%f",xxx);

return 0;
}```
Also note that your loop is not idiomatic. Most readers will see any deviation from the customary "for (i = 0; i < n; i++)" as a probable error. Your loop is correct, but would be better as "for (i=0; i<4; i++)".

Popular pages Recent additions