Write a C program to read a sentence through keyboard and to display the count ofwhite spaces in the given sentence.
Question
Write a C program to read a sentence through keyboard and to display the count ofwhite spaces in the given sentence.
Solution
Sure, here is a simple C program that counts the number of white spaces in a given sentence:
#include <stdio.h>
int main() {
char sentence[1000];
int count = 0, i;
printf("Enter a sentence: ");
gets(sentence);
for(i = 0; sentence[i] != '\0'; i++) {
if(sentence[i] == ' ' || sentence[i] == '\t' || sentence[i] == '\n')
count++;
}
printf("Number of white spaces: %d", count);
return 0;
}
Here's how it works:
-
We first include the standard input/output library using
#include <stdio.h>. -
We declare the main function where our program starts.
-
Inside the main function, we declare a character array
sentence[1000]to store the sentence, an integercountto store the number of white spaces, and an integerito use in the loop. -
We print a message asking the user to enter a sentence.
-
We use the
gets()function to read the sentence from the user. -
We start a loop that goes through each character in the sentence. The loop continues until it reaches the null character (
'\0'), which marks the end of the string. -
Inside the loop, we check if the current character is a space (
' '), a tab ('\t'), or a newline ('\n'). If it is, we increment the count. -
After the loop, we print the number of white spaces.
-
Finally, we return 0 to indicate that the program has finished successfully.
Similar Questions
Write a C program to input any two characters and a number (number of lines) from thekeyboarddisplayatriangleasshowninbelowfigure.Thetwocharactersshouldfillthetrianglein every other place
Write a C program to read an English Alphabet through keyboard and display whetherthe given alphabet is in upper case or lower case.
Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158
Write a C program to read a sentence and replace lowercase characters with uppercase and vice versa.
letter countWrite a C program that will analyze a line of text and will print the number of words, the number of consonants, and the number of vowels in the text.Testcase:Input:Programming is fun!Output:3 // Number of words:11 // Number of consonants:5 // Number of vowels:
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.