# C Program to Read a String and find the Sum of all Digits in the String

«
»

This is a C program to read a string and find the sum of all digits in the string.

Problem Description

This program takes a string containing both digits and alphabet as input and finds the sum of all digits in the string.

Problem Solution

1. Take the string as input.
2. Check for the digits in the string.
3. Count the number of digits and add all the digits to get the sum.

Program/Source Code

Here is source code of the C program to read a string and find the sum of all digits in the string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. ` `
2. ` `
3. `/*`
4. ` * C program to find the sum of all digits present in the string`
5. ` */`
6. `#include <stdio.h>`
7. `void main()`
8. `{`
9. `    char string;`
10. `    int count, nc = 0, sum = 0;`
11. ` `
12. `    printf("Enter the string containing both digits and alphabet \n");`
13. `    scanf("%s", string);`
14. `    for (count = 0; string[count] != '\0'; count++)`
15. `    {`
16. `        if ((string[count] >= '0') && (string[count] <= '9'))`
17. `        {`
18. `            nc += 1;`
19. `            sum += (string[count] - '0');`
20. `        }`
21. `    }`
22. `    printf("NO. of Digits in the string = %d\n", nc);`
23. `    printf("Sum of all digits = %d\n", sum);`
24. `}`
Program Explanation

1. Take the string containing both digits and alphabet as input and store it in the array string[].
2. Using for loop and if statement check for the digits in the array. If it is, then increment the variable nc by 1 and increment the variable sum with the current digit.
3. Do the step-2 till the end of the input string.
4. Variable nc gives the count of number of digits in the array and variable sum gives the sum of all the digits in the array.

Runtime Test Cases
```Enter the string containing both digits and alphabet
hello100
NO. of Digits in the string = 3
Sum of all digits = 1```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms 