Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function that accepts a pointer to a C-string as an argument and returns

ID: 3539207 • Letter: W

Question

Write a function that accepts a pointer to a C-string as an argument and returns the number of words contained in the string.


Write another function that accepts a pointer to a C-string as an argument and returns the average number of letters in each word (or average word size) contained in the string, rounded to 2 decimal places.


For instance, if the string argument is "Four score and seven years ago" the first function (word count) should return the number 6, and the second function (average word size) should return 4.17 (25 / 6).


Demonstrate the functions in a program that asks the user to input a string. The program should dynamically allocate just enough memory to store that string. Then the program should pass the string to the 2 functions. Both the number of words and the average word size should be displayed on the screen.

Explanation / Answer

#include <iostream>

using namespace std;
int wordcount(char *sentence)
{
    int i,count=1;
    for(i=0;sentence[i]!='';i++)
    {
        if(sentence[i]==' ')
        count++;
    }
    return count;
}

float averagewordsize(char *sentence)
{
    int i;
    float letters=0,spaces=1;
    for(i=0;sentence[i]!='';i++)
    {
        if(sentence[i]!=' ')
        letters++;
        else
        spaces++;
    }
    return letters/spaces;
}

int main()
{
   char sentence[]="Four score and seven years ago";
   cout <<wordcount(sentence)<<endl;
    std::cout.setf(std::ios::fixed);
    std::cout.precision(2);
cout<<averagewordsize(sentence)<<endl;
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote