
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Average Word Length of a Sentence in C
Problem
Enter a sentence at run time and write a code for calculating the average length of words that are present in a sentence
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()) != '
' 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 != '
') if it trues enter into loop 1. if(*stmt != ' ') 2. charcount++; 3. else if(*stmt == ' ') 4. wordcount++; 5. stmt++; iii. return (double)charcount/wordcount; STOP
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()) != '
') i++; stmt[i]='
'; avglen=calculatewordlength(stmt); printf("average length of word is:%f.
", avglen); } double calculatewordlength(const char *stmt){ int charcount=0; int wordcount=1; while(*stmt != '
'){ if(*stmt != ' ') charcount++; else if(*stmt == ' ') wordcount++; stmt++; } return (double)charcount/wordcount; }
Output
enter any statement:Tutorials Point is the best resource for online education average length of word: 5.444444444.
Advertisements