Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 20, 2017 in C program by anonymous
0 votes
1 answer
asked Apr 20, 2017 in C program by anonymous
BJSHUB - is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.

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

0 votes
asked Apr 20, 2017 in C program by anonymous

1 Answer

0 votes

This C Program reads string and find the sum of all digits in the string. The program accepts a character string, then add all the character’s integer value, thereby summing all the digits of a string.

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

$ cc pgm80.c
$ a.out
Enter the string containing both digits and alphabet
hello100
NO. of Digits in the string = 3
Sum of all digits = 1
answered Apr 20, 2017 by anonymous
...