Sums of ASCII values of each word in a sentence in c programming

In C programming, calculating the sum of ASCII values of each word in a sentence involves finding the ASCII value of each character and adding them up word by word. This technique is useful for text processing and string analysis tasks.

Syntax

int asciiValue = (int)character;
// or simply
int asciiValue = character;

Example

Here's how to calculate the sum of ASCII values for each word in a sentence −

#include <stdio.h>
#include <string.h>

void calculateWordSums(char str[]) {
    int wordSum = 0;
    int totalSum = 0;
    int wordCount = 0;
    
    printf("ASCII sums for each word: ");
    
    for (int i = 0; i <= strlen(str); i++) {
        if (str[i] == ' ' || str[i] == '\0') {
            if (wordSum > 0) {
                printf("%d ", wordSum);
                totalSum += wordSum;
                wordCount++;
                wordSum = 0;
            }
        } else {
            wordSum += (int)str[i];
        }
    }
    
    printf("\nTotal sum: %d<br>", totalSum);
    printf("Number of words: %d<br>", wordCount);
}

int main() {
    char sentence[] = "I love tutorials point";
    
    printf("Original sentence: %s<br>", sentence);
    calculateWordSums(sentence);
    
    return 0;
}
Original sentence: I love tutorials point
ASCII sums for each word: 73 438 999 554 
Total sum: 2064
Number of words: 4

How It Works

  • Character Processing: Each character is converted to its ASCII value using type casting.
  • Word Separation: Spaces are used as delimiters to separate words.
  • Sum Calculation: ASCII values are accumulated for each word until a space or end of string is encountered.
  • Output: Individual word sums and total sum are displayed.

Key Points

  • ASCII values range from 0 to 127 for standard characters.
  • Capital letters have different ASCII values than lowercase letters (A=65, a=97).
  • The algorithm handles multiple spaces by checking if wordSum > 0 before processing.
  • Using strlen(str) ensures the last word is processed when the loop reaches the null terminator.

Conclusion

This approach efficiently calculates ASCII value sums for each word in a sentence using simple character iteration and ASCII conversion. The method is straightforward and handles edge cases like multiple spaces between words.

Updated on: 2026-03-15T11:28:19+05:30

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements