Home > front end >  sum of all the digit of a number using while-loop in C
sum of all the digit of a number using while-loop in C

Time:10-07

I'm trying to solve a problem (as the title already state). I've actually learned that I can do it with modulo operator (%). But the first code that I wrote is using the while-loop, so I'm trying to finish the code.

This is the code

int main()
{
 char arr[1000000];
 int i = 0;
 int sum = 0;

    printf("type the number = ");
    scanf("%s", arr);

    while(arr[i] != '\0'){
        sum = arr[i]   sum;
        i  ;
}

printf("the total number is = %d", sum);

so the problem is it's actually printing out some huge amount of number.. I guess it's because of the array is in char, can someone help me how do I changed the value into int ?

CodePudding user response:

  1. You need to substract from the digit code the code of '0'.

Here you have the both versions (I have added some logic to accept the numbers with & - at there beginning):


int sumdigitsStr(const char *num)
{
    int sum = 0;
    int first = 1;
    while(*num)
    {
        if(isdigit(*num)) {sum  = *num - '0'; first = 0;}
        else 
        if(first && (*num == '-' || *num == ' '))
        {
            first = 0;
            num  ;
            continue;
        }
        else
        { 
            sum = -1; break;
        } //error string contains non digits
        num  ;
    }
    return sum;
}

int sumdigits(long long num)
{
    int sum = 0;
    do
    {
        sum  = abs((int)(num % 10));
    }while((num = num / 10));
    return sum;
}

CodePudding user response:

#include<stdio.h>
int main()
{
int n;
    scanf("%d",&n);
    int d,sum=0;
    while(n!=0)
    {
        d = n%10;
        sum = sum   d;
        n = n/10;
        }
    printf("sum of digits is : %d",sum);
    return 0;
}
  •  Tags:  
  • c
  • Related