Report the average number of letters per word. - C String

C examples for String:char array

Description

Report the average number of letters per word.

Demo Code

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main(void){
  int ch;//from  w  w  w. jav  a2  s  .co m
  bool in_word = false;
  int letter_count = 0, word_count = 0;

  while ((ch = getchar()) != EOF)  {
    if (isalpha(ch)) // if ch is a letter
    {
      letter_count++;
      if (!in_word) {
        in_word = true;
        word_count++;
      }
    }
    else 
      in_word = false;
  }
  printf("Average letters per word: %.2f\n", (float) letter_count / word_count);

  return 0;
}

Result


Related Tutorials