Click here to Skip to main content
15,886,782 members
Please Sign up or sign in to vote.
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
Comments
jeron1 7-Nov-22 13:37pm    
Maybe use the (absolute value) abs() function in your printf statement?

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

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;
}
 
Share this answer
 
Comments
Bogdan Alexandru Oct2022 7-Nov-22 13:45pm    
thanks.worked
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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900