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

Question 3 (10 marks). Write a program that prompts the user to enter a sentence

ID: 3603811 • Letter: Q

Question

Question 3 (10 marks). Write a program that prompts the user to enter a sentence (assume that a sentence carn have a maximum of 50 characters). It then counts the vowels and consonants in it. It also calculates the average word length of the input sentence. Word length is the total number of characters in the sentence divided by the total number of words in it. Words are separated by one or more spaces. All the results are displayed at the end. Please follow the given sample input/output. Hint: use fgets instead of scanf. Call your source code file Name the c file "lastnameFirstnameA2Q3.c". (Ritu's file would be called chaturvediRituA2Q3.c) Sample Input: Enter a sentence: today is thursday Output: Number of vowels in the sentence = 5 Number of consonants in the sentence 10 Average word length: 5.0

Explanation / Answer

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
char str[MAX_SIZE];
int i, len, vowel, consonant;

/* Input string from user */
printf("Enter any string: ");//Display user input
gets(str);

vowel = 0;
consonant = 0;
len = strlen(str);//Taking string length

for(i=0; i<len; i++)//for loop for checking vowel and consonant
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
/*
* If the current character(str[i]) is a vowel
*/
if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' ||
str[i] =='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U' )//Checking aeiou only
vowel++;
else
consonant++;
}
}

printf("Total number of vowel = %d ", vowel);
printf("Total number of consonant = %d ", consonant);
  
  
  
  
int ch;
int numWords = 0;
int numLetters = 0;
bool prevWasASpace = true; //spaces at beginning are ignored

printf("Enter a sentence: ");
while ((ch = getchar()) != EOF && ch != ' ')
{
if (ch == ' ')
prevWasASpace = true;
else
{
if (prevWasASpace)
numWords++;
prevWasASpace = false;
numLetters++;
}
}

if (numWords > 0)
{
double avg = numLetters / (float)(numWords);
printf("Average word length: %.1f (C = %d, N = %d) ", avg, numLetters, numWords);
}
  

return 0;
}

=====================

Enter any string: this is word
Total number of vowel:=3
Total number of consonant =7

Enter a sentence: this is word

Average word length:4

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