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
*/
#include <stdio.h>
void main()
{
char string[80];
int count, nc = 0, sum = 0;
printf("Enter the string containing both digits and alphabet \n");
scanf("%s", string);
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
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for C Internship
- Check C Books