Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. We first include the standard input/output library using #include <stdio.h>.

  2. We declare the main function where our program starts.

  3. Inside the main function, we declare a character array sentence[1000] to store the sentence, an integer count to store the number of white spaces, and an integer i to use in the loop.

  4. We print a message asking the user to enter a sentence.

  5. We use the gets() function to read the sentence from the user.

  6. 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.

  7. 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.

  8. After the loop, we print the number of white spaces.

  9. Finally, we return 0 to indicate that the program has finished successfully.

This problem has been solved

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;}

1/2

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.