w3resource

C Exercises: Sum of all numerical values (positive integers) embedded in a sentence


Sum numerical values embedded in a sentence

Write a C program to sum all numerical values (positive integers) embedded in a sentence.

Input:
Sentences with positive integers are given over multiple lines. Each line is a character string containing one-byte alphanumeric characters, symbols, spaces, or an empty line. However the input is 80 characters or less per line and the sum is 10,000 or less

Sample Solution:

C Code:

#include <stdio.h>
#include <stdlib.h>

// Define a character array to store text
char text[128];

int main(void) {
  int i, j, k;
  int result = 0;
  char temp[8];

  // Prompt user to input sentences with positive integers
  printf("Input Sentences with positive integers:\n");

  // Read user input into the 'text' array
  scanf("%s", text);

  i = 0;
  while (text[i]) {
    // Loop through characters until a digit is found
    for (; (text[i] < '0' || '9' < text[i]) && text[i]; i++);

    if ('0' <= text[i] && text[i] <= '9') {
      // Extract and store the numerical value in 'temp'
      for (j = 0; '0' <= text[i] && text[i] <= '9'; j++, i++) {
        temp[j] = text[i];
      }

      temp[j] = '\0';
      // Convert 'temp' to an integer and add it to 'result'
      result += atoi(temp);
    }
  }

  // Print the sum of all numerical values embedded in the sentence
  printf("\nSum of all numerical values embedded in a sentence:\n");
  printf("%d\n", result);

  return 0;
}

Sample Output:

Input Sentences with positive integers:
5littleJackand2mouse.

Sum of all numerical values embedded in a sentence:
7

Flowchart:

C Programming Flowchart: Sum of all numerical values (positive integers) embedded in a sentence.


For more Practice: Solve these Related Problems:

  • Write a C program to scan a sentence and extract all integers, then compute their sum using character parsing.
  • Write a C program to use pointer arithmetic to traverse a string and sum embedded numerical values.
  • Write a C program to implement a function that identifies and sums all numeric substrings within a given sentence.
  • Write a C program to parse a sentence for digits, convert them to integers, and accumulate their total using loops.

Go to:


PREV : Maximum regions formed by nnn straight lines.
NEXT : Extract words of 3 to 6 characters from a sentence.

C programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.