C Program to calculate sum of all Integers of a string

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

How to count integers in a string also find sum?

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

In this c program, we accept a string 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 the 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.

Explain the if condition in c?

The syntax of the if condition statement i.


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 the variable string as a type of character.

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

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

STEP 6: Check if string[count]>0 and string[count]<=9 then nc=nc+1,sum=sum+string[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.

C Source Code

                                          #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++) /* check the string for any integers */ {
    if ((string[count] >= '0') && (string[count] <= '9')) /* check and add the integers  in to a variable called sum  */ {
      nc += 1;
      sum += (string[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