Contact Learn C
Copy

Program 93:To print sum of digits in string

Program 93:To print sum of digits in string
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
int i,j=0,temp,sum=0,n;
char str1[100],str2[100]={0};
printf("Enter a string\n");
gets(str1);

for(i=0;i<strlen(str1);i++)
{
    if(str1[i]>='0'&&str1[i]<='9')
    {
        str2[j]=str1[i];
        j++;
    }
    
}
temp=atoi(str2);//To convert string to integer
printf("The digits present in string is %d\n",temp);
while(temp>0)
{
    n=temp%10;
    sum+=n;
    temp=temp/10;
}
printf("The sum of digits is %d\n",sum);

}
Explanation:

  1. This program starts with initializing :
    • temp → To store only digits from string temporarily as a number integer format
    • i,j,n→Used as helping variable
    • sum → To store output sum
    • str1 →To store input string
    • str2  →To store digits in string format
  2. printf("Enter a string\n");
    gets(str1);
    
    Taking input from user.Let it be "he123"
  3. for(i=0;i<strlen(str1);i++)
    {
        if(str1[i]>='0'&&str1[i]<='9')
        {
            str2[j]=str1[i];
            j++;
        }
        
    }
    The above for loop traverse from 0 to length of string which here is 5(he123).
    Each time it iterates from 0 it checks whether the character lies in between 0 and 9 and if it is ,then that character which lies in between 0 and 9 is stored in str2 one by one
  4. Finally all the digits are stored in str2 in string format 
  5. temp=atoi(str2);
    atoi will convert string to integer and that is stored in temp=123
  6. while(temp>0)
    {
        n=temp%10;
        sum+=n;
        temp=temp/10;
    }
    printf("The sum of digits is %d\n",sum);
    Now temp will have 123 in("he123").The above forloop will get us sum of the digits.If you would like to understand how that works see this Program 8:Sum of all Digits
  7. Finally sum of 123 is 6


 Output:

To print sum of digits in string
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide