Exercise 1.8 - Count blanks, tabs and newlines

Question

Write a program to count blanks, tabs, and newlines.

Solution

/***
 *
 * Write a program to count blanks, tabs and newlines.
 *
 **/

#include <stdio.h>

int main() {
    int c, blanks, tabs, newlines;

    blanks = tabs = newlines = 0;

    while ((c = getchar()) != EOF) {
        if (c == ' ')
            ++blanks;
        if (c == '\t')
            ++tabs;
        if (c == '\n')
            ++newlines;
    }

    printf("Blanks: %d\n", blanks);
    printf("Tabs: %d\n", tabs);
    printf("Newlines: %d\n", newlines);
}

Explanation

In this program we are going to count the number of Blanks, tabs and new lines present in the input. To do this the program, while reading the characters checks for the condition c = getchar !=EOF which means if the character is not end of file continue counting Blanks tabs and newlines. Example input:

I like programming In C And the out put shall be: Blanks: 4 Tabs: 0 Newlines: 1