Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Count Number of Words in a String


Write a C program to count number of words in a string.

  • Reads the input string character by character until a newline is encountered.
  • Initializes a flag (inWord) to track whether the current position is inside a word.
  • Increments the word count when a non-space character is found following a space or at the beginning.
  • Prints the total number of words identified by transitions from space to non-space characters.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[200];
    int i = 0, wordCount = 0;
    int inWord = 0;

    printf("Enter a string: ");
    while ((str[i] = getchar()) != '\n') {
        i++;
    }
    str[i] = '\0';

    // Count words
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] != ' ' && inWord == 0) {
            wordCount++;
            inWord = 1;
        } else if (str[i] == ' ') {
            inWord = 0;
        }
    }

    printf("Number of words: %d\n", wordCount);

    return 0;
}

Output :

Enter a string: This is a sample C program
Number of words: 6