15,747,169 members
1.00/5 (1 vote)
See more:
i have to print the sum of digits of a number

```int main ()
{
int num, sum = 0;
scanf("%d" , &num);
while(num!=0){
sum += num % 10;
num = num / 10;
}

printf("the sum of the digits is %d",sum);

return 0;
}```

i write this but is i have a negative number let s say -35 i need the result to be 8 and my program is printing -8..how can i solve this ?

What I have tried:

i can t figure it out i tried..........
Posted
Updated 7-Nov-22 7:41am
v2
jeron1 7-Nov-22 13:37pm
Maybe use the (absolute value) abs() function in your printf statement?

printf("Suma cifrelor este %d",abs(sum));

## Solution 1

If you want to ignore the negative sign then you can treat all numbers as being positive so one way to do that is to make any negative number be a positive one. Here's one way you can do that :
C
```int main ()
{
int num, sum = 0;
scanf("%d" , &num);

if( num < 0 )
num *= -1;   // change a negative number to be positive

while(num!=0){
sum += num % 10;
num = num / 10;
}

printf("Suma cifrelor este %d",sum);

return 0;
}```

Bogdan Alexandru Oct2022 7-Nov-22 13:45pm
thanks.worked

## Solution 2

Convert input to an absolute value.

C++
```int main ()
{
int num, sum = 0;
scanf("%d" , &num);
num = abs(num);   // Convert to absolute value
while(num!=0){
sum += num % 10;
num = num / 10;
}

printf("Suma cifrelor este %d",sum);

return 0;
}```