Home > Backend Development > C++ > body text

Write a C program to calculate the average word length of sentences using a while loop

WBOY
Release: 2023-08-28 18:25:06
forward
1416 people have browsed it

Write a C program to calculate the average word length of sentences using a while loop

Question

Enter a sentence at runtime and write a code to calculate the average length of words appearing in the sentence

Solution Solution

Algorithm
START
Step 1: declare character, int and double variables
Step 2: Enter any statement
Step 3: while loop
       Check condition stmt[i]=getchar()) != &#39;</p><p>&#39;
       True then enter into loop
       Increment I and call the function at step 5
Step 4: Print the average length return by function
       From step 5
Step 5: called function calculatewordlength
         i. declare and initialize
            charcount=0 and wordcount=1
         ii. while loop
            check condition (*stmt != &#39;</p><p>&#39;)
            if it trues enter into loop
            1.    if(*stmt != &#39; &#39;)
            2.    charcount++;
            3.    else if(*stmt == &#39; &#39;)
            4.    wordcount++;
            5.    stmt++;
         iii. return (double)charcount/wordcount;
STOP
Copy after login

Program

#include<stdio.h>
#include<string.h>
double calculatewordlength(const char *stmt);
int main(){
   char stmt[100];
   int i=0;
   double avglen;
   printf("enter any statement:");
   while((stmt[i]=getchar()) != &#39;</p><p>&#39;)
      i++;
   stmt[i]=&#39;</p><p>&#39;;
   avglen=calculatewordlength(stmt);
   printf("average length of word is:%f.</p><p> ", avglen);
}
double calculatewordlength(const char *stmt){
   int charcount=0;
   int wordcount=1;
   while(*stmt != &#39;</p><p>&#39;){
      if(*stmt != &#39; &#39;)
         charcount++;
      else if(*stmt == &#39; &#39;)
         wordcount++;
      stmt++;
   }
   return (double)charcount/wordcount;
}
Copy after login

Output

enter any statement:Tutorials Point is the best resource for online education average length of word: 5.444444444.
Copy after login

The above is the detailed content of Write a C program to calculate the average word length of sentences using a while loop. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!