C Program to calculate sum of all Integers of a string


April 20, 2022, Learn eTutorial
1761

How to count integers in a string and also find its sum?

In this C program, we need to calculate the number of integers in a string and its sum. For example, consider a string "learn C programming 12", where we have two integers, so make the count as '2' and the sum of the integers as '1 + 2 = 3'.

To implement this program logic in C, we accept a value from the user with both integers and alphabets. Start a for loop from zero to the end of the string to check if there any integers. Then inside a for loop check the string character is greater than zero and less than or equal to 9 using an 'if' condition. if so, increment the counter by 1 and add that number to the sum. Finally, we display the output as the sum of integers in a string, both sum, and count.

The syntax of the if condition statement is.


if (testExpression) {

  // codes inside the body of if

} 

If the test expression is True, we execute the if statement. But if the test expression is False, We skip the code inside the if statement.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the integer variable count,nc,sum and set nc=0,sum=0.

STEP 3: Declare a variable as a type of character.

STEP 4: Read from the user into the variable string.

STEP 5: By using the for loop set count=0,check str[count]!='\0' then do step 6.

STEP 6: Check if str[count]>0 and str[count]<=9 then nc=nc+1,sum=sum+str[count]-0.

STEP 7: Display the number of digits in the string as NC.

STEP 8: Display the Sum of all digits as a sum.


To count the integers in a string in C. we need to learn the below topics, please refer to those for a better understanding

C Source Code

                                          #include <stdio.h>

void main() {
  char str[80];
  int count, nc = 0, sum = 0;
  printf("Enter the string containing both digits and alphabet\n");
  scanf("%s", & str);
  for (count = 0; str[count] != '\0'; count++) /* check the string for any integers */ {
    if ((str[count] >= '0') && (str[count] <= '9')) /* check and add the integers  in to a variable called sum  */ {
      nc += 1;
      sum += (str[count] - '0');
    } /* End of if */
  } /* End of For */
  printf("NO. of Digits in the string=%d\n", nc);
  printf("Sum of all digits=%d\n", sum);
} /* End of main() */
                                      

OUTPUT

Enter the string containing both digits and alphabet
goodmorning25

NO. of Digits in the string=2
Sum of all digits=7