Average Character
Question
Solution
Idea
The basic idea is easy, just to get the average ASCII value of each character in the input string.
However, if C is the language being used, things get a bit tricky regarding the input. Here, we can only use fgets()
to read the input because white space characters cannot be ignored in this question. So, the correct way to read the input is below:
#define MAX_LEN 102
if (fgets(string, MAX_LEN, stdin))
{
string[strcspn(string, "\n")] = 0;
}
Code
https://github.com/mendax1234/Coding-Problems/blob/main/kattis/averagecharacter/averagecharacter.c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 102
char get_average_ascii(char string[MAX_LEN])
{
long i = 0;
long sum = 0;
while(string[i] != 0)
{
sum += (long)string[i];
i += 1;
}
long avg = sum / i;
return (char)avg;
}
int main()
{
char string[MAX_LEN];
if (fgets(string, MAX_LEN, stdin))
{
string[strcspn(string, "\n")] = 0;
}
putchar(get_average_ascii(string));
}
Last updated