w3resource

C Exercises: Count blanks, tabs, and newlines in an input text.

C Basic Declarations and Expressions: Exercise-96 with Solution

Count blanks, tabs, and newlines in a text input

Write a C program to count blanks, tabs, and newlines in input text.

Sample Solution:

C Code:

#include <stdio.h>

int main() {
int blank_char, tab_char, new_line; // Variables to count blank characters, tab characters, and newlines
blank_char = 0; // Initialize the count of blank characters
tab_char = 0; // Initialize the count of tab characters
new_line = 0; // Initialize the count of newlines
int c; // Variable to hold input characters

printf("Number of blanks, tabs, and newlines:\n");
printf("Input few words/tab/newlines\n");

  // Loop to read characters until end-of-file (EOF) is encountered
for (; (c = getchar()) != EOF;) {
if (c == ' ') {
      ++blank_char; // Increment the count of blank characters
    }
if (c == '\t') {
      ++tab_char; // Increment the count of tab characters
    }
if (c == '\n') {
      ++new_line; // Increment the count of newlines
    }
  }

  // Print the final counts of blanks, tabs, and newlines
printf("blank=%d,tab=%d,newline=%d\n", blank_char, tab_char, new_line);
}

Sample Output:

Number of blanks, tabs, and newlines:
Input few words/tab/newlines
The quick
brown fox jumps
over the lazy dog
^Z
blank=7,tab=2,newline=3

Flowchart:

C Programming Flowchart: Count blanks, tabs, and newlines in an input text.

C programming Code Editor:

Previous:Write a C program to print the corresponding Fahrenheit to Celsius and Celsius to Fahrenheit.
Next: Write a C program to replace more than one blanks with a single blank in a input string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/basic-declarations-and-expressions/c-programming-basic-exercises-96.php