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 of white 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 integercount
to store the number of white spaces, and an integeri
to 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
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 an English Alphabet through keyboard and display whetherthe given alphabet is in upper case or lower case.
Write a C program to read a sentence and replace lowercase characters with uppercase and vice versa.
IPS5-Pointer5Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158
Find output of the below program:int main(){ char str[]={'e','a','r','t','h'}; printf("%s", str); return 0;}
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.