Calculate sum of all numbers present in a string
sum-of-all-digits-present-in-a-string |
#include<stdio.h>
#include<string.h>
using namespace std;
int SumOfDigits(string str, int n);
int SumOfoverallNumberPresent_In_Sequence(string str, int n);
int main()
{
char str[20];
printf("Please enter the string:");
gets(str);
int length = strlen(str);
cout<<"\n\nsum of all digits present in string is :- "<<SumOfDigits(str, length)<<endl;
cout<<"\n\nSum of different numbers present in string:- "<<SumOfoverallNumberPresent_In_Sequence(str, length)<<endl;
return 0;
}
int SumOfDigits(string str, int n)
{
int i,sum=0,num=0;
for(i = 0;i<=n;i++)
{
if(str[i] >=48 && str[i] <= 57)
{
num = str[i]-48;
sum = sum + num;
}
}
return sum;
}
int SumOfoverallNumberPresent_In_Sequence(string str, int n)
{
int i,sum=0,digitSum=0,Flag=0,num=0;
for(i = 0;i<=n;i++)
{
if(str[i] >=48 && str[i] <= 57)
{
num = str[i]-48;
sum = sum*10 + num;
}
else
{
digitSum = digitSum+sum;
sum=0;
}
}
return digitSum;
}
Other Articles:
Kth smallest element , Merge Point In LinkList, Compare two String Represented in Link-List
Article Sources For Learning
Other Blogs: Follow here
0 comments:
Post a Comment