This is a C program to read a string and find the sum of all digits in the string.
This program takes a string containing both digits and alphabet as input and finds the sum of all digits in the string.
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.
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.
* C program to find the sum of all digits present in the string
int count, nc = 0, sum = 0;
printf("Enter the string containing both digits and alphabet \n");
for (count = 0; string[count] != '\0'; count++)
if ((string[count] >= '0') && (string[count] <= '9'))
nc += 1;
sum += (string[count] - '0');
printf("NO. of Digits in the string = %d\n", nc);
printf("Sum of all digits = %d\n", sum);
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.
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 Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Apply for Computer Science Internship
- Apply for C Internship
- Practice BCA MCQs
- Buy Computer Science Books
- Buy C Books