forked from sachin-nono/codingpractice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSumOfDigitsString.cpp
More file actions
61 lines (44 loc) · 1.01 KB
/
SumOfDigitsString.cpp
File metadata and controls
61 lines (44 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Sum Of The Digits
Take as input a number in the form of a string.
Write a recursive function that returns the sum of the digits in the string.
*/
#include<iostream>
using namespace std;
int main()
{
char str[10];
long sum, SumOfDigits(char []);
bool correctFormat(char []), x;
cout<<"Enter the number : ";
cin>>str; //as 'cin>>' will ignore white spaces and tabs
x=correctFormat(str);
if(x==1)
{
sum=SumOfDigits(str);
cout<<"\nSum of digits of the number is : "<<sum<<endl;
}
else
cout<<"\nEntered number contains some special characters also!!!\n";
return 0;
}
bool correctFormat(char str[])
{
for(int i=0; str[i]!='\0'; ++i)
if(!(isdigit(str[i])))
return false;
return true;
}
int i=0;
long sum=0, x;
long SumOfDigits(char str[])
{
if(str[i]!='\0')
{
x=str[i]-'0';
sum+=x;
++i;
SumOfDigits(str);
}
return sum;
}