Average of ASCII values of characters of a given string?

In C programming, calculating the average of ASCII values of characters in a string involves summing all character ASCII values and dividing by the string length. For example, the string "ABC" has ASCII values 65, 66, 67, giving an average of 66.

Syntax

float calculateAsciiAverage(char str[]);

Algorithm

asciiAverage(String)

Begin
   sum := 0
   for each character c in String, do
      sum := sum + ASCII of c
   done
   return sum/length of String
End

Example

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

float calculateAsciiAverage(char str[]) {
    int sum = 0;
    int length = strlen(str);
    
    for (int i = 0; i < length; i++) {
        sum += (int)str[i];
    }
    
    return (float)sum / length;
}

int main() {
    char str[100];
    
    printf("Enter a string: ");
    scanf("%s", str);
    
    float average = calculateAsciiAverage(str);
    printf("ASCII average is: %.2f<br>", average);
    
    return 0;
}

Output

Enter a string: Hello
ASCII average is: 100.00

How It Works

  • The function iterates through each character in the string
  • Each character is cast to int to get its ASCII value
  • All ASCII values are summed up
  • The sum is divided by string length to get the average
  • Result is returned as float for decimal precision

Conclusion

Calculating ASCII average in C involves summing character values and dividing by string length. This technique is useful for text analysis and character distribution studies in programming applications.

Updated on: 2026-03-15T11:01:39+05:30

961 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements