Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
intto 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
floatfor 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.
Advertisements
