Extract Digits From a Number and Make a Sum of all the digits and show this in C

Code is here:

#include<stdio.h>
int main()
{
    int number;
    scanf("%d",&number);
    char digits[2000000];
    int i=0,d;
    while(number>0)
    {
        d=number%10;
        digits[i]=d; //putting the values in char array //as we have put the int value so we are using %d
        //printf("%s",digits);
        number=number/10;   //it is diving to get one digit number as we looping till zero (0)
        ++i; //pre incrementing  the value of i
    }
    digits[i]='\0';  //char array last value is this 
  //  printf("%d\n",i);
    int t,sum=0;
    for(t=i-1; t>=0; t--) //we need i-1 as it is just before the null value of the array
    {
        printf("%d\t",digits[t]); //printing values from  saved char array 
        sum=sum+digits[t]; //summing all the values of this array
    }
    printf("\n Sum of all digits = %d",sum);

    return 0;
}

Output:

88567
8       8       5       6       7
 Sum of all digits = 34

Modular Beautiful Code: 😀

Actually array return function is not directly possible in C and I am finding the solution here.

Took Slightly Help From this link:
https://cboard.cprogramming.com/c-programming/150996-extracting-digits-integer.html

http://mathforum.org/library/drmath/view/56002.html

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *