IN C LANGUAGE 1) Prompt the user to enter a sentence 2) read in AT MOST 80 chara
ID: 3811538 • Letter: I
Question
IN C LANGUAGE
1) Prompt the user to enter a sentence 2) read in AT MOST 80 characters of the sentence the user entered 3) count the number of words in the sentence by looking for whitespace (space, tab) 4) print out the number of words in the sentence (that was at most 80 characters
The idea:
User inputs: A long sentence that will get us started on the lab so that we can see what is really going on here
Your code should only read in A long sentence that will get us started on the lab so that we can see what is r
And count the number of words and report the results: The 80 characters read were: A long sentence that will get us started on the lab so that we can see what is r and they contained 19 words
IN C LANGUAGE
Explanation / Answer
PLEASE FIND THE BELOW CODE:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BUFFERSIZE 81 // 80 characters plus end of string
int main (int argc, char *argv[])
{
char sentence [BUFFERSIZE];
//1. Prompt user to enter a sentence.
printf("Enter a sentence: ");
//2. Read atmost 80 characters of the sentence the user entered.
fgets(sentence, BUFFERSIZE, stdin);
//printf("%s ", sentence);
//3. Count number of words in the sentence, by looking for white spaces.
int numOfWords = 1;
for(int i = 0; i < strlen(sentence); i++)
{
if(sentence[i] == ' ')
{
numOfWords++;
while(sentence[i] == ' ')
i++;
}
}
//4. Print out number of words in the sentence.
printf("The number of words in the sentence is: %d ", numOfWords);
return 0;
}